0tokens

Apply for AI Grants India

Financial support for innovators building the future of AI in India.

Apply now

Chat · how to use webmcp for ai agents to query the bhashini translation api

How to Use WebMCP for AI Agents to Query the Bhashini Translation API

  1. aigi

    AI agents become substantially more useful when they can call reliable tools instead of merely generating text. For Indian-language applications, one valuable integration is the Bhashini Translation API: it can help agents translate user requests, responses, documents, and workflow data across supported Indian languages. WebMCP provides a browser-facing way to expose website capabilities as structured tools that an agent can discover and invoke.

    This guide explains how to use WebMCP for AI agents to query the Bhashini Translation API, including the architecture, request flow, tool design, authentication, JavaScript implementation patterns, security controls, testing, and production considerations. Because Bhashini endpoints, models, and access requirements can change, verify the current API documentation and credentials before deployment.

    What WebMCP and Bhashini solve together

    WebMCP is a mechanism for making web application actions available to AI agents as typed, discoverable tools. Instead of asking an agent to guess an API URL or construct arbitrary HTTP requests, you expose a narrowly defined operation such as translateText with a JSON input schema.

    Bhashini is India’s language technology ecosystem, offering access to services such as:

    • Text translation between supported Indian and international languages
    • Automatic speech recognition and text-to-speech through participating models
    • Language identification and other language AI capabilities, depending on the selected service

    Together, WebMCP and Bhashini can support multilingual customer support, government-service interfaces, education platforms, voice assistants, vernacular search, and localization pipelines.

    The recommended pattern is not to expose Bhashini credentials directly to a browser agent. Instead, WebMCP invokes your application’s server-side proxy, which validates the request, selects an approved Bhashini service, adds credentials, calls the API, and returns a normalized result.

    Reference architecture

    A production integration normally contains five layers:

    1. User interface — A web page receives text, language preferences, or an agent task.
    2. WebMCP tool layer — The page publishes a constrained translation tool for compatible agents.
    3. Application backend — A server endpoint validates inputs and enforces quotas.
    4. Bhashini gateway or service API — The backend sends the request using the current Bhashini authentication and payload format.
    5. Response normalizer — The backend converts provider-specific output into a stable response for the agent.

    The flow is:

    AI agent
       ↓ discovers and calls
    WebMCP: translateText
       ↓ HTTPS request
    Your backend /api/translate
       ↓ authenticated provider request
    Bhashini translation service
       ↓ normalized JSON
    Agent receives translated text and metadata

    This separation is important. It prevents provider-specific details from leaking into the browser and lets you change models or Bhashini service configurations without changing the agent-facing tool contract.

    Prerequisites before implementation

    Prepare the following before writing code:

    • A Bhashini account, approved access, and the credentials required by the selected service
    • The current Bhashini API documentation for the translation pipeline you intend to use
    • A backend runtime such as Node.js, Python, Java, or Go
    • A web page or web application that can register WebMCP tools
    • A list of supported source and target language codes
    • Request limits, maximum text length, timeout, and cost controls
    • A test set containing English and Indian-language examples, including Unicode edge cases

    Do not assume that every Bhashini model supports every language pair. Maintain an explicit capability map in your backend and reject unsupported combinations before making an external request.

    Design a safe WebMCP tool schema

    A tool schema should describe the smallest useful operation. Avoid exposing a generic callBhashiniApi tool with arbitrary URLs, headers, or provider payloads. That design increases prompt-injection risk and makes validation difficult.

    A useful translation tool can accept:

    {
      "sourceLanguage": "en",
      "targetLanguage": "hi",
      "text": "Where is the nearest railway station?",
      "formality": "neutral"
    }

    Recommended validation rules include:

    • sourceLanguage: required string restricted to an allowlist
    • targetLanguage: required string restricted to an allowlist
    • text: required Unicode string with a strict maximum length
    • formality: optional enum, only if your selected model supports it
    • No client-provided URL, API key, arbitrary headers, or model identifier

    Return a stable response such as:

    {
      "translatedText": "निकटतम रेलवे स्टेशन कहाँ है?",
      "sourceLanguage": "en",
      "targetLanguage": "hi",
      "provider": "bhashini",
      "requestId": "internal-request-id"
    }

    Do not return secrets, internal stack traces, raw authorization headers, or unnecessary provider data. A stable schema helps agents interpret the result reliably.

    Registering a WebMCP translation tool

    WebMCP implementations and browser support may evolve, so use the current WebMCP specification and feature-detection pattern for your target environment. A conceptual browser-side implementation looks like this:

    const translationInput = {
      type: "object",
      additionalProperties: false,
      properties: {
        sourceLanguage: {
          type: "string",
          enum: ["en", "hi", "bn", "ta", "te", "mr", "gu", "kn", "ml", "pa"]
        },
        targetLanguage: {
          type: "string",
          enum: ["en", "hi", "bn", "ta", "te", "mr", "gu", "kn", "ml", "pa"]
        },
        text: { type: "string", minLength: 1, maxLength: 5000 }
      },
      required: ["sourceLanguage", "targetLanguage", "text"]
    };
    
    async function translateText({ sourceLanguage, targetLanguage, text }) {
      const response = await fetch("/api/translate", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        credentials: "same-origin",
        body: JSON.stringify({ sourceLanguage, targetLanguage, text })
      });
    
      if (!response.ok) {
        const message = await response.text();
        throw new Error(`Translation failed: ${response.status} ${message}`);
      }
    
      return response.json();
    }
    
    if (navigator.modelContext) {
      navigator.modelContext.registerTool({
        name: "translateText",
        description: "Translate a short text between supported languages using the application language service.",
        inputSchema: translationInput,
        execute: translateText
      });
    }

    The exact registration API may differ depending on the WebMCP implementation available in your browser or agent framework. Treat the example as an integration pattern: feature-detect support, publish a typed tool, call your own backend, and normalize the response.

    Build the server-side Bhashini adapter

    The backend should be the only component that knows how to authenticate with Bhashini. Keep provider code in an adapter so that the rest of your application depends on an internal interface rather than a vendor-specific payload.

    An Express-style example:

    import express from "express";
    
    const app = express();
    app.use(express.json({ limit: "32kb" }));
    
    const SUPPORTED = new Set(["en", "hi", "bn", "ta", "te", "mr", "gu", "kn", "ml", "pa"]);
    
    function validate(body) {
      const { sourceLanguage, targetLanguage, text } = body ?? {};
    
      if (!SUPPORTED.has(sourceLanguage) || !SUPPORTED.has(targetLanguage)) {
        throw new Error("Unsupported language code");
      }
      if (typeof text !== "string" || text.trim().length === 0 || text.length > 5000) {
        throw new Error("Text must contain 1 to 5000 characters");
      }
      return { sourceLanguage, targetLanguage, text: text.trim() };
    }
    
    app.post("/api/translate", async (req, res) => {
      const requestId = crypto.randomUUID();
    
      try {
        const input = validate(req.body);
    
        // Construct this payload according to the current Bhashini documentation.
        const providerPayload = {
          input: [{ source: input.text }],
          config: {
            sourceLanguage: input.sourceLanguage,
            targetLanguage: input.targetLanguage
          }
        };
    
        const providerResponse = await fetch(process.env.BHASHINI_TRANSLATE_URL, {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
            "Authorization": `Bearer ${process.env.BHASHINI_API_KEY}`
          },
          body: JSON.stringify(providerPayload),
          signal: AbortSignal.timeout(15000)
        });
    
        if (!providerResponse.ok) {
          throw new Error(`Provider status ${providerResponse.status}`);
        }
    
        const data = await providerResponse.json();
        const translatedText = extractTranslation(data);
    
        return res.json({
          translatedText,
          sourceLanguage: input.sourceLanguage,
          targetLanguage: input.targetLanguage,
          provider: "bhashini",
          requestId
        });
      } catch (error) {
        console.error({ requestId, error: error.message });
        return res.status(400).json({ error: "Translation request could not be completed", requestId });
      }
    });

    The extractTranslation function should be written against the exact response format returned by your selected Bhashini pipeline. Avoid blindly returning the entire response. Validate that the translated field exists, is a string, and is within a reasonable size.

    Authentication and secrets

    Never place a Bhashini API key in:

    • WebMCP tool definitions
    • Client-side JavaScript bundles
    • HTML source
    • Local storage or URL query parameters
    • Agent-visible tool results

    Store credentials in a server-side secret manager or protected environment variables. Rotate them periodically and use separate credentials for development, staging, and production. If Bhashini requires specific headers, pipeline identifiers, or authorization tokens, add them only in the backend adapter.

    Use HTTPS end to end. Add authentication to your own /api/translate endpoint when the tool is not intended for anonymous access. For browser sessions, combine same-origin protections, CSRF defenses where applicable, and strict CORS policies.

    Agent behavior and prompt-injection controls

    An agent may encounter untrusted webpage text that instructs it to change tools, reveal credentials, or translate sensitive data. WebMCP does not eliminate this risk; it makes tool governance more important.

    Apply these controls:

    • Require explicit user intent before translating sensitive content.
    • Mark the tool as a translation operation, not a general network tool.
    • Restrict languages, text length, and request frequency server-side.
    • Do not allow agent-supplied endpoint or credential parameters.
    • Log tool invocation metadata without storing raw sensitive text unnecessarily.
    • Redact personal information from application logs where possible.
    • Require confirmation for bulk translation or paid operations.

    For Indian deployments, consider data residency, sector-specific requirements, and contractual obligations before sending personal, health, financial, or government records to any external language service.

    Error handling and retries

    Translation failures should be understandable to both the agent and the user. Return machine-readable categories such as:

    • INVALID_LANGUAGE_PAIR
    • TEXT_TOO_LONG
    • AUTHENTICATION_FAILED
    • PROVIDER_TIMEOUT
    • RATE_LIMITED
    • UNSUPPORTED_CONTENT
    • TEMPORARY_PROVIDER_ERROR

    Retry only transient failures, such as timeouts or HTTP 5xx responses. Use exponential backoff with jitter and a low retry limit. Do not retry invalid input or authentication failures. Set a total deadline so an agent does not wait indefinitely.

    A useful error response is:

    {
      "error": {
        "code": "RATE_LIMITED",
        "message": "Translation is temporarily busy. Try again shortly.",
        "retryable": true,
        "requestId": "abc-123"
      }
    }

    Testing the integration

    Test at three levels.

    Schema tests

    Verify that the WebMCP tool rejects missing fields, unknown properties, unsupported language codes, empty strings, and oversized inputs. Test Unicode normalization, emoji, punctuation, Devanagari, Bengali, Tamil, Telugu, Kannada, Malayalam, Gujarati, Gurmukhi, and mixed-script text.

    Adapter tests

    Mock Bhashini responses and verify that your adapter:

    • Sends the expected language configuration
    • Adds credentials server-side
    • Extracts the correct translated field
    • Handles provider errors and malformed responses
    • Enforces timeouts and retry policies

    End-to-end tests

    Use a staging credential and a small fixed corpus. Measure latency, translation quality, failure rate, and output preservation for names, numbers, URLs, HTML, Markdown, and placeholders. For business-critical content, add human review by native speakers rather than relying only on automated similarity scores.

    Performance, cost, and quality optimization

    For interactive agents, keep inputs short and return only the translation needed for the current task. Cache deterministic translations when policy permits, using a key based on source language, target language, text, model configuration, and version. Avoid caching sensitive content without a defined retention policy.

    Useful production metrics include:

    • WebMCP tool-call success rate
    • Backend validation failure rate
    • Bhashini latency at p50, p95, and p99
    • Provider timeout and rate-limit counts
    • Translation output size
    • Cost or quota consumption
    • User correction and fallback rates

    Preserve placeholders such as {name}, %s, HTML tags, and Markdown links. If translating structured content, translate only approved text fields and retain the original object structure.

    Common implementation mistakes

    Calling Bhashini directly from the browser

    This exposes credentials and makes abuse easier. Use a backend proxy.

    Exposing arbitrary provider controls

    Letting an agent choose any model, URL, or header creates a broad and unsafe tool. Use allowlists and server-side configuration.

    Assuming language codes are universal

    Language identifiers differ between providers and pipelines. Maintain an explicit mapping and validate it.

    Returning raw provider responses

    Provider payloads may change and can contain internal metadata. Normalize them.

    Treating translation as authoritative

    Machine translation can misunderstand context, dialect, names, and legal wording. Add human review where consequences are high.

    Ignoring mixed-language Indian input

    Real users often combine English with Hindi or another regional language. Include code-mixed examples in testing and define fallback behavior for language identification.

    Practical deployment checklist

    Before production launch, confirm that:

    • The current Bhashini endpoint and payload format have been verified.
    • API keys are stored outside client code.
    • WebMCP registration is feature-detected and has a non-agent UI fallback.
    • Input schemas and backend validation enforce the same limits.
    • Supported language pairs are documented and tested.
    • Timeouts, retries, quotas, and rate limits are configured.
    • Logs include request IDs but avoid unnecessary sensitive text.
    • Provider responses are normalized and malformed output is rejected.
    • Monitoring and alerts cover failures and latency.
    • Privacy, consent, retention, and Indian regulatory requirements are reviewed.

    FAQ

    Can WebMCP call the Bhashini Translation API directly?

    It can technically invoke a browser request only when the endpoint supports the required browser security policy and does not require secret credentials. In production, expose a WebMCP tool that calls your authenticated server-side adapter instead.

    Which languages can I translate with Bhashini?

    Availability depends on the selected Bhashini service, model, and language pair. Do not hard-code assumptions; check the current capability documentation and maintain an application allowlist.

    Should the agent send the full conversation for translation?

    Usually no. Send the smallest relevant text, preserve structured fields and placeholders, and apply privacy controls before transmission. Full conversation translation increases latency, cost, and data exposure.

    Is WebMCP supported in every browser?

    WebMCP availability may vary by browser, version, and agent runtime. Use capability detection and provide a normal user-facing translation button or backend workflow as a fallback.

    Apply for AI Grants India

    Building an Indian-language AI agent, translation workflow, or WebMCP integration? Apply to AI Grants India for support, visibility, and opportunities designed for Indian AI founders.

AIGI may be inaccurate. Replies seeded from the guide above.