WebMCP can make browser-based tools discoverable and usable by AI agents through structured capabilities, typed inputs, and predictable outputs. For Marathi news sentiment analysis, the challenge is not only exposing a tool: you must handle Devanagari text, Indian-language context, code-mixing, headlines, negation, and the difference between a news article’s tone and the sentiment of quoted speakers.
This guide explains how to build a production-oriented WebMCP tool for agents to analyze sentiment in Marathi news articles. It assumes a web application or service that exposes a sentiment function through a WebMCP-compatible interface and optionally calls a Marathi NLP model or inference API.
What the WebMCP sentiment tool should do
The tool should accept Marathi news content and return a machine-readable analysis that an AI agent can use without guessing field meanings. A minimal capability could:
- Accept an article title and body in Marathi.
- Detect the dominant sentiment: positive, negative, neutral, or mixed.
- Return a confidence score.
- Provide sentence-level sentiment where useful.
- Identify the language and flag code-mixed text.
- Explain important signals without reproducing unnecessary personal data.
- Report validation or model errors explicitly.
A useful tool name might be analyze_marathi_news_sentiment. Its description should tell agents when to use it and when not to use it. For example, it should be designed for editorial or article-level sentiment analysis—not for determining whether a political claim is true, predicting election outcomes, or judging an individual’s character.
Recommended architecture
A robust implementation separates browser-facing tool registration from NLP inference:
1. WebMCP tool layer: Defines the tool name, description, input schema, output schema, and invocation handler.
2. Validation layer: Checks text length, required fields, encoding, and optional parameters.
3. Preprocessing layer: Normalizes Unicode, preserves sentence boundaries, and detects Marathi, English, and code-mixed content.
4. Inference layer: Calls a Marathi-capable model locally or through a controlled API.
5. Post-processing layer: Calibrates confidence, aggregates sentence scores, and creates a stable response.
6. Observability layer: Records latency, failures, model version, and anonymized quality metrics.
Keeping inference behind a server-side endpoint is generally safer. Do not expose private model credentials or unrestricted inference APIs in browser JavaScript. If the WebMCP runtime executes in a browser, the handler can call your backend over HTTPS, with authentication, rate limits, and origin controls.
Design a precise input schema
Agents perform better when inputs are explicit and constrained. Use JSON Schema or the schema format required by your WebMCP implementation. A practical input contract could look like this:
{
"type": "object",
"properties": {
"title": {
"type": "string",
"description": "Marathi news headline, if available",
"maxLength": 1000
},
"article_text": {
"type": "string",
"description": "Main article text in Marathi or Marathi-English code-mixed text",
"minLength": 20,
"maxLength": 50000
},
"granularity": {
"type": "string",
"enum": ["document", "sentence"],
"default": "document"
},
"include_explanation": {
"type": "boolean",
"default": false
}
},
"required": ["article_text"],
"additionalProperties": false
}The title should be optional because some agents may extract article text without a headline. Set a realistic maximum length to prevent accidental overload. You may also add a source_url, but treat it as metadata rather than a retrieval instruction. If the tool is not intended to fetch pages, state that clearly and reject URLs as article content.
Define a stable output contract
The output should be predictable enough for an agent to summarize, filter, compare, or store results. Avoid returning only a prose paragraph. Include a label, scores, scope, and model metadata.
{
"language": {
"primary": "mr",
"code_mixed": true
},
"document_sentiment": {
"label": "negative",
"scores": {
"positive": 0.08,
"negative": 0.76,
"neutral": 0.16
},
"confidence": 0.76
},
"sentence_results": [],
"limitations": [
"Sentiment reflects linguistic tone, not factual accuracy."
],
"model": {
"name": "your-marathi-sentiment-model",
"version": "2026-01"
}
}Ensure probabilities are numbers between 0 and 1 and sum to approximately 1. A mixed document can be represented as a separate label or derived when sentence-level polarity is sharply divided. Choose one convention and document it. For agent interoperability, include a human-readable explanation only as an optional field, while keeping the primary result structured.
Choose a Marathi-capable NLP model
Marathi sentiment analysis requires more than an English sentiment classifier with Devanagari support. Evaluate models trained or adapted for Marathi and Indian multilingual text. Candidate approaches include:
- A Marathi-specific transformer fine-tuned on labelled news or social text.
- A multilingual Indic model fine-tuned for sentiment classification.
- A hosted inference endpoint with documented Marathi performance.
- A hybrid pipeline that uses a classifier plus lexicons and rule-based checks.
Before selecting a model, inspect its training domain. A model trained on product reviews may perform poorly on political reporting. News articles frequently contain neutral narration, emotionally charged quotations, and event descriptions that are negative in consequence but neutral in journalistic tone.
For a custom model, create a labelled dataset with at least these categories: positive, negative, neutral, and mixed. Ask multiple Marathi-speaking annotators to label the same examples and resolve disagreements with written guidelines. Include regional vocabulary, formal Marathi, transliterated Marathi, English entities, names, abbreviations, and headlines with omitted verbs.
Marathi preprocessing considerations
Unicode normalization is essential. Devanagari text may contain visually identical sequences with different combining marks. Normalize input consistently, but avoid transformations that remove meaningful punctuation or alter named entities.
Useful preprocessing steps include:
- Normalize Unicode to a consistent form.
- Convert unusual whitespace and line breaks safely.
- Preserve danda punctuation (
।) and sentence-ending punctuation. - Detect Devanagari, Latin, numerals, and other scripts.
- Keep hashtags, mentions, and URLs available as optional features.
- Normalize common spelling variants only if validated on your dataset.
- Detect Marathi-English code-mixing instead of forcing all text into one language.
Do not blindly translate Marathi into English and classify the translation. Translation can lose negation, honorific nuance, idioms, political terminology, and intensity. If you use translation as a fallback, return a warning and measure its accuracy separately.
Handle news-specific sentiment correctly
News sentiment is ambiguous. An article reporting a flood may contain strongly negative events while maintaining neutral editorial language. A political article may quote an angry statement without endorsing it. Your tool should state what it measures: the linguistic sentiment or emotional polarity of the supplied text.
Consider returning separate fields for:
- Narrative tone: sentiment of the article’s own reporting.
- Quoted sentiment: sentiment inside quotations.
- Headline sentiment: polarity of the headline alone.
- Event polarity: whether described events are beneficial or harmful, if your model supports that task.
Do not claim these dimensions are interchangeable. If your first version supports only document sentiment, expose a scope field and include a limitation such as: “The result may reflect quoted language and descriptions of adverse events.”
Negation deserves special testing. Marathi constructions can reverse or weaken polarity, and punctuation can affect meaning. Build test cases containing words such as “नाही” and common negative constructions, but rely on model evaluation rather than a small hand-written list alone.
Implement the WebMCP handler
The exact registration API depends on the WebMCP runtime and browser or framework version. Keep the implementation conceptually simple: register one narrowly defined tool, validate arguments, invoke the backend, and return structured JSON.
Illustrative TypeScript-style pseudocode:
registerTool({
name: "analyze_marathi_news_sentiment",
description:
"Analyze the linguistic sentiment of Marathi or Marathi-English news text. " +
"Do not use this to verify facts or predict political outcomes.",
inputSchema: marathiSentimentInputSchema,
async execute(input, context) {
const parsed = validateInput(input);
const response = await fetch("/api/sentiment/marathi", {
method: "POST",
headers: {
"Content-Type": "application/json",
"X-Request-ID": context.requestId
},
body: JSON.stringify(parsed)
});
if (!response.ok) {
throw new Error("Sentiment service unavailable");
}
return await response.json();
}
});Use the official WebMCP documentation for the current registration and permission APIs. The important engineering principles remain the same: strict schemas, bounded input, typed output, explicit errors, and no hidden side effects.
Build the inference API
Your backend endpoint should validate again because client-side validation is not a security boundary. A typical request flow is:
1. Verify authentication and request origin where applicable.
2. Enforce body size and text-length limits.
3. Normalize and classify the input language.
4. Run the model with a timeout.
5. Calibrate or threshold confidence.
6. Return model version and limitations.
7. Emit metrics without storing raw article text by default.
For long articles, chunk by sentence rather than arbitrary character count. Aggregate sentence probabilities using a documented method, such as a length-weighted mean with headline weighting. Test multiple aggregation strategies because a single highly negative sentence can dominate a short article unfairly.
Security, privacy, and responsible use
News text may include names, phone numbers, addresses, or sensitive allegations. Apply data minimization:
- Do not log complete article bodies unless necessary and consented.
- Redact personal data in diagnostic logs.
- Encrypt traffic with HTTPS.
- Rate-limit tool calls and cap concurrency.
- Prevent prompt injection if article text is passed to an LLM anywhere in the pipeline.
- Treat article text as untrusted data, not instructions.
- Restrict server-side fetches to prevent SSRF if URL ingestion is added.
- Publish retention, deletion, and processing policies.
Sentiment outputs should not be used alone for moderation, hiring, credit, policing, or political targeting. In India, consider applicable privacy obligations, organizational policies, and the sensitivity of political and public-interest content. A confidence score is not proof of correctness; it should communicate uncertainty, not create false authority.
Evaluate accuracy and agent usability
Measure both NLP quality and tool quality. For the classifier, report macro-F1, per-class precision and recall, confusion matrices, calibration error, and performance across code-mixed and regional subsets. Accuracy alone can hide a model that predicts neutral too often.
Create a test suite containing:
- Short and long Marathi headlines.
- Formal and colloquial writing.
- Positive, negative, neutral, and mixed articles.
- Negation and sarcasm.
- Quoted speech.
- Disaster, crime, health, sports, business, and political coverage.
- Devanagari-only and Marathi-English code-mixed text.
- Empty, oversized, malformed, and non-Marathi inputs.
For WebMCP behavior, test whether agents can discover the capability, supply valid arguments, interpret labels, handle errors, and respect limitations. Version your schema carefully. Renaming article_text to text without compatibility planning can break agent workflows even if the model itself is unchanged.
Deployment checklist
Before production, verify:
- The tool description accurately states scope and limitations.
- Input and output schemas reject unexpected fields.
- API keys remain server-side.
- Timeouts and retry policies are bounded.
- Model version is returned with each result.
- Health checks distinguish API failure from model failure.
- Metrics track latency, error rate, token or compute usage, and confidence distribution.
- Marathi quality is reviewed by native or highly proficient speakers.
- A fallback response explains when the model cannot classify reliably.
- The interface is tested in the browsers and agent runtimes you support.
Start with document-level analysis, then add sentence-level output after you have sufficient evaluation data. A narrowly scoped, reliable tool is more useful to agents than a broad tool with ambiguous semantics.
FAQ
Can an English sentiment model analyze Marathi news?
It may process Devanagari text, but that does not guarantee Marathi accuracy. Use a Marathi-capable or Indic multilingual model and validate it on representative Marathi news data.
Should the tool fetch Marathi articles from URLs?
Not by default. Accepting supplied text reduces security, copyright, extraction, and SSRF risks. If URL fetching is required, use an allowlist, safe retrieval service, content limits, and clear permission controls.
What should the tool return when confidence is low?
Return an explicit uncertain state or a low confidence score, explain the limitation, and avoid forcing a positive, negative, or neutral label when the model is unreliable.
Is sentiment analysis the same as misinformation detection?
No. Sentiment measures linguistic polarity or tone. It does not establish whether a Marathi news claim is true, false, biased, or legally actionable.
Apply for AI Grants India
Building an India-focused AI tool for Marathi language technology, agent infrastructure, or responsible news analysis? Apply to AI Grants India for potential support, visibility, and opportunities to advance your project.