WebMCP is best understood as a controlled bridge between AI agents running in a browser and structured web capabilities. For hyperlocal delivery on the Open Network for Digital Commerce (ONDC), the right design is not a browser agent that directly calls every network participant. It is a layered architecture in which WebMCP exposes narrow, typed tools; an orchestration layer converts user intent into an ONDC-compliant search and order flow; and a trusted backend handles credentials, signatures, callbacks, payments, and fulfillment state.
For example, a user might ask: “Find organic milk and bread available near Koramangala and deliver them within 45 minutes.” The WebMCP should collect location and preferences, invoke a delivery-search capability, present comparable offers, and request confirmation before placing an order. It should not expose private ONDC keys or allow an unreviewed model to submit arbitrary protocol payloads.
The recommended architectural pattern
The most suitable pattern is a tool-mediated, agent-assisted gateway architecture:
User
|
Browser AI agent
|
WebMCP tool layer (typed capabilities, consent, validation)
|
Application orchestrator / policy engine
| \
ONDC gateway State store + event processor
| |
ONDC network Beckn/ONDC callbacks, order state, delivery updates
|
Buyer, seller, logistics and payment participantsThis pattern combines several established ideas:
- Model Context Protocol-style tool exposure: the agent sees documented functions rather than unrestricted HTTP access.
- API gateway: requests are authenticated, rate-limited, logged and normalized.
- Saga orchestration: search, selection, confirmation, payment and fulfillment are treated as a distributed transaction with compensating actions.
- Event-driven state management: ONDC callbacks, webhook events and delivery updates update a durable order state machine.
- Human-in-the-loop controls: high-impact actions such as payment or order confirmation require explicit consent.
The WebMCP is therefore the agent-facing presentation layer, not the ONDC protocol implementation itself.
Why direct browser-to-ONDC integration is risky
ONDC uses interoperable, multi-party commerce flows based on the Beckn protocol. A typical transaction involves a buyer network participant, seller network participant, logistics providers and payment services. Network calls and callbacks must be correlated, validated and retained over time.
A direct browser implementation creates several problems:
- Credential exposure: signing keys, private tokens and participant credentials cannot be placed in JavaScript delivered to a browser.
- Untrusted model actions: an AI agent could submit an order, accept substitutions or trigger payment without adequate confirmation.
- Callback reachability: seller and logistics callbacks need a stable, server-side endpoint; a browser tab is not a reliable webhook receiver.
- Protocol complexity: ONDC message construction, headers, signatures, encryption, timestamps and error handling belong in a controlled backend.
- Privacy leakage: precise location, phone numbers and addresses may be sent to more participants than necessary.
- Poor reliability: mobile networks, closed tabs and browser sleep states can interrupt long-running order workflows.
Use WebMCP for discovery and interaction, while a backend performs privileged network operations.
Core components of a WebMCP–ONDC system
1. Browser agent and WebMCP client
The browser agent interprets natural-language requests and calls approved tools. The tool descriptions should specify:
- Required inputs and data types
- Location precision and permitted area
- Whether the tool is read-only or transactional
- Expected response schema
- Freshness requirements
- Consent requirements
- Failure and retry behavior
Avoid a generic tool such as send_ondc_request(payload). Prefer bounded capabilities such as:
find_delivery_offerscompare_catalog_itemsget_delivery_quotecreate_cart_previewrequest_order_confirmationtrack_delivery
Each tool should return structured data suitable for rendering, not raw protocol noise.
2. WebMCP capability gateway
The gateway validates tool calls before forwarding them. It should enforce JSON Schema validation, authentication, authorization, quotas and request context. It can also apply policy rules, such as:
- Do not reveal an exact address until the user confirms a compatible seller.
- Do not place an order without a fresh confirmation token.
- Do not exceed a user-defined budget.
- Do not substitute products unless substitutions are enabled.
- Do not send a location outside the user’s selected service area.
The gateway should attach a correlation ID to every operation. That ID must remain consistent across search requests, selections, confirmations and callbacks.
3. Intent and orchestration service
The orchestrator translates user intent into a deterministic workflow. It should separate four stages:
1. Interpretation: extract product, quantity, location, delivery window, budget and constraints.
2. Planning: choose the appropriate ONDC domain, city or geographic context and search strategy.
3. Execution: create protocol-compliant requests and process responses.
4. Presentation: rank offers transparently and ask for confirmation.
An LLM may assist with interpretation and ranking, but it should not be the source of truth for prices, stock, delivery fees or order status. Those values must come from validated network responses.
4. ONDC adapter and protocol services
The ONDC adapter isolates the rest of the system from protocol-specific details. It is responsible for:
- Constructing search, select, init, confirm, status, track, cancel and rating messages as applicable
- Adding required context, domain, city, transaction and message identifiers
- Managing authentication, signing and encryption requirements
- Sending requests through the configured network participant or gateway
- Validating response schemas and participant data
- Correlating asynchronous callbacks
- Applying retry, timeout and idempotency rules
Keep the adapter versioned. ONDC APIs and implementation requirements can evolve, and different domains or network roles may have distinct operational expectations.
5. Callback and event processor
The callback service is essential for ONDC commerce. Search responses may arrive asynchronously, and order status, fulfillment and cancellation events can change after the initial interaction.
A robust processor should:
- Verify callback authenticity and schema
- Check transaction and message identifiers
- Reject stale or duplicated events safely
- Store the raw event for audit purposes
- Publish a normalized internal event
- Update the order state machine transactionally
- Notify the browser agent or user interface
Use an event queue for resilience. The user-facing interface can receive updates through WebSockets, server-sent events or polling, while the backend remains the durable source of truth.
The hyperlocal search flow
A practical query flow looks like this:
Step 1: Capture structured intent
Convert the request into a typed object:
{
"items": [
{"query": "organic milk", "quantity": 1},
{"query": "whole wheat bread", "quantity": 1}
],
"delivery_area": {
"lat": 12.9352,
"lon": 77.6245,
"precision": "neighbourhood"
},
"max_delivery_minutes": 45,
"max_total_inr": 800,
"substitutions": false
}The application should normalize units, identify ambiguous products and ask follow-up questions before searching.
Step 2: Resolve location safely
Hyperlocal delivery depends on serviceability, so location handling is central. Obtain consent before accessing browser geolocation. Prefer approximate coordinates during discovery and collect the full delivery address only when required for selection or fulfillment.
India-specific considerations include apartment names, landmarks, PIN codes, gated communities and inconsistent address formats. Use a canonical internal address model, but retain the user’s original text for clarification.
Step 3: Discover offers through ONDC
The ONDC adapter sends a compliant search request using the appropriate buyer-side network path. Responses may include multiple sellers, catalogs, prices, taxes, packaging fees, delivery estimates and fulfillment options.
Normalize these responses into a common offer model. Do not merge items from different sellers into one cart unless the network flow and user experience explicitly support split orders.
Step 4: Rank with explainable rules
The agent can rank offers using user preferences, but ranking should be transparent. Useful signals include:
- Total landed price in INR
- Estimated delivery time
- Item availability and quantity
- Seller distance or serviceability
- Delivery fee and surge fee
- Seller rating, where available
- Return, cancellation and substitution policies
Show why an offer was selected: “Fastest eligible option,” “Lowest total price,” or “Best match for organic products.” Never claim that a seller is better based on unavailable or inferred facts.
Step 5: Select and confirm
Once the user chooses an offer, the backend performs the next protocol steps and obtains current fulfillment and payment information. Prices and availability should be revalidated before payment or final confirmation.
Use a short-lived confirmation token containing the selected offer ID, payable amount, expiry time and user constraints. If any material value changes, require confirmation again.
Order state and saga design
ONDC workflows are distributed, so use a state machine rather than a single synchronous request. Typical internal states include:
INTENT_CAPTUREDSEARCHINGOFFERS_RECEIVEDOFFER_SELECTEDQUOTE_VALIDATEDPAYMENT_PENDINGORDER_CONFIRMEDFULFILLMENT_ASSIGNEDOUT_FOR_DELIVERYDELIVEREDCANCEL_REQUESTEDCANCELLEDFAILED
Every transition should define accepted events, timeout behavior and user-visible messaging. For example, if a payment succeeds but confirmation is delayed, the system must not blindly retry and risk a duplicate order. Idempotency keys and reconciliation jobs are mandatory.
Security, privacy and consent
A WebMCP for commerce should apply zero-trust principles:
- Keep ONDC credentials and signing keys in a server-side secrets manager.
- Use TLS for all transport and encrypt sensitive data at rest.
- Scope access tokens by user, tool and operation.
- Apply CSRF protection and origin checks to browser requests.
- Validate tool arguments against strict schemas.
- Rate-limit search and confirmation endpoints.
- Redact addresses, phone numbers and payment references from logs.
- Maintain an immutable audit trail for consent and transactional actions.
- Provide deletion and retention controls aligned with India’s Digital Personal Data Protection requirements.
Consent must be specific and understandable. “Find stores near me” is different from “place this order and pay ₹640.” The interface should display seller, items, quantities, fees, delivery estimate and total amount immediately before confirmation.
Reliability and observability
Hyperlocal delivery is sensitive to latency and stale information. Instrument the full path with:
- Search latency by network participant and city
- Callback delay and failure rate
- Offer freshness and price-change frequency
- Tool-call rejection reasons
- Confirmation conversion rate
- Duplicate and idempotency conflicts
- Order state transition failures
- Delivery SLA performance
Use distributed tracing with correlation IDs, structured logs and dead-letter queues. Cache only data that can safely be stale, such as catalog metadata. Do not cache availability, delivery promises or prices beyond their stated validity.
A multi-region deployment may be useful for scale, but data residency, operational cost and participant connectivity should guide the decision. For an early India-focused product, a resilient primary region, managed queue and well-tested disaster recovery plan are often more valuable than premature global complexity.
Recommended API and tool boundaries
A clean internal API might expose these endpoints:
POST /v1/intent/parsePOST /v1/delivery/searchPOST /v1/offers/{id}/selectPOST /v1/orders/{id}/confirmGET /v1/orders/{id}POST /v1/orders/{id}/cancelGET /v1/orders/{id}/trackingPOST /v1/ondc/callbacks
The browser should call the application API or WebMCP gateway, never the privileged ONDC adapter directly. Return stable application schemas so the agent is insulated from protocol changes.
Common architectural mistakes
Avoid these failure modes:
- Exposing a raw ONDC request tool to an LLM
- Treating asynchronous callbacks as optional
- Using the model’s generated price or ETA instead of validated response data
- Sending precise location before it is necessary
- Combining seller offers without modeling split fulfillment
- Retrying payment or confirmation without idempotency
- Letting tool descriptions omit side effects
- Building the demo around one city or one participant and assuming network-wide behavior
- Failing to preserve raw protocol messages for dispute resolution and debugging
A practical implementation roadmap
Start with a read-only MVP:
1. Implement typed WebMCP tools for location, product search and offer comparison.
2. Build a server-side ONDC adapter with schema validation and correlation IDs.
3. Add callback ingestion, normalized offer storage and observability.
4. Introduce selection and quote revalidation.
5. Add confirmation, payment and order state management with idempotency.
6. Add tracking, cancellation, substitution policies and human support escalation.
7. Test with sandbox or approved network environments before production rollout.
Measure both technical and user outcomes: successful searches, accurate totals, median time to offer, confirmation errors and completed deliveries.
FAQ
Should WebMCP call ONDC directly from the browser?
No. Keep protocol credentials, signatures, callbacks and transactional logic on a trusted backend. WebMCP should expose constrained capabilities through an authenticated gateway.
Can an AI agent place a hyperlocal delivery order automatically?
Technically, it can orchestrate the workflow, but payment and final confirmation should normally require explicit user consent. Apply budget, seller and substitution policies before allowing automation.
What is the most important ONDC integration component?
The callback-aware orchestration layer is critical. It must manage asynchronous responses, order state, retries, idempotency and reconciliation across buyer, seller, logistics and payment participants.
How should location privacy be handled in India?
Use approximate location for discovery, request precise address details only when needed, minimize retention and clearly explain which data is shared with commerce and logistics participants.
Apply for AI Grants India
If you are an Indian AI founder building a WebMCP, ONDC integration or agentic commerce product, apply to AI Grants India for support and funding opportunities. Share your technical architecture, pilot evidence and India-specific impact.