Real-time mandi prices are valuable only when farmers and agricultural agents can access them in a clear, trustworthy, and timely way. A WebMCP tool can expose mandi-price data as a structured capability that AI agents call on demand—for example, to answer “What is today’s tomato price near Nashik?” or “Which nearby mandi is offering the best price for green gram?”
This guide explains how to create a WebMCP tool for agents to fetch real-time mandi prices, using India-aware data modelling, API integration, validation, security controls, and practical deployment patterns. The goal is not merely to connect an AI model to an endpoint, but to create a dependable agricultural data interface that handles market names, commodities, units, grades, dates, and location ambiguity correctly.
What is WebMCP?
WebMCP is a web-oriented approach for making application capabilities available to AI agents through well-defined tools. Instead of asking an agent to scrape a website or guess API parameters, you expose a tool with:
- A clear name and description
- A strict input schema
- A predictable output schema
- Authentication and authorization rules
- Error handling and rate limits
- Human-readable metadata and machine-readable fields
For mandi prices, the tool might be named fetch_mandi_prices. An agent can call it with a commodity, state, district, market, date range, or language preference. The WebMCP layer then validates the request, retrieves data from an approved source, normalizes the response, and returns evidence the agent can cite.
A useful architecture is:
Farmer or user
↓
AI agent
↓
WebMCP tool: fetch_mandi_prices
↓
Validation, authorization, caching
↓
Mandi data adapter
↓
Agmarknet or approved market-data APIThe tool should not invent prices, silently substitute commodities, or present an old cached value as current. Data freshness and provenance are core product requirements.
Define the mandi-price use case precisely
Before writing code, define what “real-time mandi prices” means for your application. In India, agricultural price records commonly include several distinct values:
- Min price: Lowest reported price for the selected record
- Max price: Highest reported price
- Modal price: Most frequently observed or representative price
- Arrival quantity: Produce quantity arriving at the market
- Trade date: Date associated with the market report
- Variety: Produce variety or grade
- Unit: Often quintal, kilogram, tonne, or another market-specific unit
A farmer asking for “today’s onion price” may mean the modal price for a specific mandi, while an agent comparing markets may need minimum, maximum, modal, arrivals, distance, and update time.
Write down the initial scope. A practical version-one tool can support:
- One or more commodities
- State, district, and market filters
- A date or date range
- Variety and grade where available
- Price fields in the source unit
- Optional conversion to ₹/kg
- Source URL, source timestamp, and fetched timestamp
Avoid claiming live prices if your source updates daily or periodically. Use terms such as “latest reported price” and return the exact trade date.
Choose reliable Indian mandi data sources
For India-specific implementations, begin with an official or contractually permitted source. Agmarknet is a common reference point for agricultural market information, while the Open Government Data platform may provide datasets or APIs depending on the resource. Some state agricultural marketing boards and private providers also expose market feeds.
Evaluate each source on:
- Legal permission to access and redistribute data
- API availability and authentication requirements
- Update frequency
- Market and commodity identifiers
- Historical coverage
- Rate limits and uptime
- Field definitions and data quality
- Whether prices are reported per quintal or another unit
Do not build a production tool by scraping a public webpage unless the site’s terms and robots policy permit it and you have a robust maintenance plan. Scraping often breaks when HTML changes, and it can create duplicate, stale, or incorrectly parsed records.
Create a source adapter rather than embedding a provider’s response format directly into the agent-facing tool. This lets you change providers without breaking the WebMCP contract.
Design the WebMCP tool contract
A good tool contract is narrow, explicit, and easy for an agent to use. For example:
{
"name": "fetch_mandi_prices",
"description": "Fetch the latest reported wholesale mandi prices for an agricultural commodity in India. Returns min, max, and modal prices with trade date, unit, market, and source metadata.",
"inputSchema": {
"type": "object",
"properties": {
"commodity": { "type": "string" },
"state": { "type": "string" },
"district": { "type": "string" },
"market": { "type": "string" },
"variety": { "type": "string" },
"tradeDate": { "type": "string", "format": "date" },
"limit": { "type": "integer", "minimum": 1, "maximum": 50 },
"language": { "type": "string", "enum": ["en", "hi"] }
},
"required": ["commodity"]
}
}The actual WebMCP registration syntax depends on the SDK or browser integration you use, but the principles remain the same. Use enumerations or canonical IDs wherever possible. Free-text values such as “Bangalore,” “Bengaluru,” and “Bengaluru APMC” should be resolved through a controlled lookup layer.
Consider separating discovery from retrieval:
search_mandi_locationsresolves state, district, market, and location aliases.search_commoditiesresolves commodity and variety names.fetch_mandi_pricesretrieves the actual records.
This prevents the main price tool from guessing identifiers.
Use canonical IDs and India-aware normalization
Indian agricultural data contains spelling variations, transliterations, abbreviations, and multiple administrative levels. Maintain reference tables for:
- State and Union Territory names
- District names and historical names
- Market or APMC identifiers
- Commodity identifiers
- Variety and grade identifiers
- Common Hindi and regional-language aliases
For example, map “paddy,” “rice paddy,” and a supported local-language term to a canonical commodity only when the source defines them as equivalent. Do not collapse “paddy” and “rice” if they refer to different stages of the supply chain.
A normalized internal request may look like:
{
"commodityId": "ONION",
"stateCode": "MH",
"districtCode": "NASHIK",
"marketId": "NASHIK_APMC",
"tradeDate": "2026-09-03",
"limit": 10
}Store both the user’s original text and the resolved canonical value. This helps with debugging and allows the agent to explain assumptions.
Build the data adapter and normalization layer
Your adapter should translate the source API response into a stable internal model. A normalized record can include:
{
"commodity": "Onion",
"variety": "Local",
"state": "Maharashtra",
"district": "Nashik",
"market": "Nashik",
"tradeDate": "2026-09-03",
"minPrice": 1800,
"maxPrice": 2600,
"modalPrice": 2200,
"unit": "INR/quintal",
"arrivalQuantity": 1250,
"source": "Official market data provider",
"sourceRecordId": "example-id"
}Validate every numeric field before returning it. Reject negative prices, impossible dates, missing market identifiers, and records with inconsistent ranges such as minPrice > modalPrice or modalPrice > maxPrice, unless the source documentation explicitly permits a different interpretation.
Never convert units without recording the conversion. If the source reports ₹2,200 per quintal, the equivalent is ₹22 per kilogram because one quintal equals 100 kilograms. Return both values when conversion is requested:
{
"modalPrice": 2200,
"unit": "INR/quintal",
"modalPricePerKg": 22,
"conversion": "1 quintal = 100 kg"
}Keep monetary amounts as integers in paise or as decimal-safe values internally. Avoid binary floating-point calculations for financial outputs.
Add freshness, provenance, and confidence metadata
An AI agent needs enough context to avoid overstating the result. Every response should include:
tradeDate: Date of the market transaction or reportfetchedAt: Time your service retrieved the record, preferably in ISO 8601 UTCsourceUpdatedAt: Source update time when availableisCached: Whether the result came from cachesourceNameandsourceUrlcoverageNote: Any limitation in geography, commodity, or date
Example:
{
"dataStatus": "latest_reported",
"tradeDate": "2026-09-03",
"fetchedAt": "2026-09-03T08:15:00Z",
"isCached": false,
"sourceName": "Approved mandi data source",
"records": []
}Use a freshness policy. For example, a daily dataset may be cached for 15–60 minutes during the day, but the response must still state the trade date. If the source has not updated for several days, return a warning such as stale_source_data rather than describing the price as today’s price.
Implement the server-side request flow
A secure request flow generally follows these steps:
1. Receive the WebMCP tool call.
2. Validate the JSON schema and maximum page size.
3. Resolve commodity, location, and variety aliases.
4. Check authorization, quota, and abuse controls.
5. Generate a cache key from canonical parameters.
6. Serve a valid cached response when appropriate.
7. Call the source adapter with a strict timeout.
8. Normalize and validate source records.
9. Attach freshness and provenance metadata.
10. Return structured results and a user-safe error when necessary.
Illustrative TypeScript-style pseudocode:
async function fetchMandiPrices(input: PriceQuery) {
const query = validateAndResolve(input);
const cacheKey = makeCacheKey(query);
const cached = await cache.get(cacheKey);
if (cached && !isExpired(cached)) {
return { ...cached, isCached: true };
}
const raw = await provider.fetch(query, { timeoutMs: 5000 });
const records = raw.map(normalizeRecord).filter(isValidRecord);
if (records.length === 0) {
throw new ToolError("NO_DATA", "No matching reported prices were found.");
}
const result = addProvenance(records, raw.metadata);
await cache.set(cacheKey, result, 1800);
return result;
}Keep provider credentials on the server. The agent should never receive API keys, internal endpoints, database connection strings, or unrestricted query access.
Handle agent ambiguity safely
Agents often receive incomplete farmer questions. “Price near me” requires location access or a follow-up question. “Best price” requires a definition: highest modal price, highest maximum price, or best net realization after transport costs?
Your tool should support clarification rather than guessing. Return structured states such as:
{
"status": "needs_clarification",
"missing": ["district_or_market"],
"message": "Please provide the district or mandi name to compare prices."
}For nearby-market search, accept latitude and longitude only when the user has granted permission. Calculate distance using a trusted geospatial service or a maintained market-coordinate table. Do not infer a precise farmer location from an IP address and present it as exact.
If several markets match, return candidate markets for agent confirmation. Preserve the distinction between a market’s reported price and a farmer’s expected net price. Transport, commission, loading, quality deductions, and arrivals can materially change the decision.
Design farmer-friendly agent responses
The WebMCP response should be machine-readable, while the agent’s final message should be simple and localized. A useful natural-language response might say:
> Nashik mandi reported a modal onion price of ₹2,200 per quintal on 3 September 2026. The reported range was ₹1,800–₹2,600 per quintal. This is the latest available market report, not a guaranteed farm-gate price.
For Indian users, consider:
- Hindi and regional-language labels
- Indian number formatting, such as
₹2,200 - Explicit units and quintal-to-kilogram conversion
- Voice-friendly summaries for low-literacy or mobile-first use
- A source link or “verify before dispatch” reminder
- Simple explanations of modal, minimum, and maximum prices
Do not overwhelm farmers with raw JSON. Let the tool return detailed metadata to the agent, then instruct the agent to lead with commodity, mandi, date, modal price, range, unit, and source status.
Security, privacy, and reliability controls
Even a read-only price tool needs production safeguards:
- Apply authentication for private or paid deployments.
- Enforce per-user and per-agent rate limits.
- Validate all input strings and reject oversized values.
- Use allowlisted provider domains and HTTPS.
- Keep API keys in a secret manager.
- Log tool calls without exposing personal data.
- Redact precise location unless required and consented to.
- Set provider timeouts, retries with backoff, and circuit breakers.
- Monitor empty responses, schema changes, latency, and stale data.
- Version the tool contract when fields or semantics change.
Treat prompt-injected instructions from external data as untrusted content. A mandi record, market name, or source description must never be allowed to alter tool permissions or system instructions.
Test the WebMCP mandi tool
Create automated tests for normal, ambiguous, and adversarial cases:
- Commodity only
- Commodity plus state and district
- Exact market ID
- Unknown commodity
- Misspelled market name
- Hindi or regional-language alias
- Invalid future date
- Date range exceeding the allowed window
- No matching records
- Provider timeout
- Malformed provider response
- Prices with missing modal values
- Unit conversion from ₹/quintal to ₹/kg
- Stale cached data
- Unauthorized requests
Add contract tests that compare the adapter output with your canonical schema. Use recorded fixtures where the provider permits it, and run a small set of live health checks separately so tests do not overload an official endpoint.
Evaluate answer quality, not only API correctness. Ask whether the agent identifies the trade date, uses the right unit, avoids claiming a guaranteed sale price, and asks for clarification when a location is missing.
Deployment and monitoring checklist
Before exposing the tool to farmers or production agents, verify:
- The source license and usage limits are documented.
- All prices include trade date, unit, and provenance.
- Cache TTL matches source update frequency.
- Provider failures produce honest, actionable errors.
- Market and commodity reference data has an update process.
- Logs include request ID, latency, source status, and result count.
- Metrics track freshness, cache hit rate, error rate, and p95 latency.
- Responses work on low-bandwidth mobile connections.
- Tool descriptions explain limitations clearly.
- A human support path exists for incorrect market records.
Start with a small number of commodities and states, then expand after observing real queries. Agricultural terminology and market coverage vary significantly across India; controlled expansion is safer than launching a nationwide tool with unreliable mappings.
Common mistakes to avoid
- Calling a daily report “live” without showing its trade date
- Returning only one price without identifying whether it is min, max, or modal
- Mixing ₹/kg and ₹/quintal
- Guessing a mandi from an ambiguous city name
- Scraping without permission or resilience planning
- Exposing provider keys to the browser or agent
- Letting the language model calculate authoritative prices from unstructured text
- Hiding missing records behind a confident response
- Ignoring variety, grade, or quality differences
- Treating mandi price as the farmer’s final net realization
A reliable tool is deliberately conservative. It should prefer “I need the district” or “the latest available record is two days old” over a precise-looking answer built on an unsupported assumption.
FAQ: WebMCP mandi price tools
Can an AI agent fetch mandi prices directly from a website?
It can, but a structured WebMCP tool backed by an approved API or dataset is more reliable than scraping. Use a provider adapter, validation, caching, and provenance metadata.
Which price should the agent show farmers?
Usually show the modal price first, followed by the minimum and maximum range. Always include the trade date, unit, market, variety when available, and a note that the mandi price is not a guaranteed farm-gate price.
Should prices be returned in rupees per kilogram?
Return the source unit, commonly ₹/quintal, and optionally provide a clearly labelled conversion to ₹/kg. Never silently change units.
How do I support “mandi near me” queries?
Request consented coordinates or ask for the user’s district, then resolve nearby markets using maintained market coordinates. Explain the distance and comparison method.
Is cached mandi data acceptable?
Yes, if the cache policy matches the source’s update pattern and the response clearly reports the trade date, fetch time, and whether the result is cached.
Apply for AI Grants India
Building an AI agent or WebMCP infrastructure for Indian farmers? Apply to AI Grants India for support, visibility, and potential grant opportunities for ambitious India-focused AI projects.