AI agents can make government-document workflows far more useful when they can retrieve structured information from DigiLocker—such as a verified name, date of birth, education credential, driving licence, or vehicle registration—at the right moment. However, the integration must be designed around explicit consent, strong authentication, minimal data access, and clear auditability.
This guide explains how to create a WebMCP tool for agents to extract information from DigiLocker. It focuses on a practical architecture for an agent-facing tool layer, while keeping DigiLocker authentication and sensitive operations on a trusted backend. The examples use TypeScript-style pseudocode, but the same design applies to Python, Java, Go, or an MCP-compatible gateway.
What WebMCP Means in a DigiLocker Integration
WebMCP is best understood as a web-accessible tool interface that allows an AI agent to discover and invoke narrowly defined capabilities. Instead of giving an agent unrestricted browser access or raw API credentials, you expose typed operations such as:
list_available_documentsget_document_metadataextract_document_fieldsverify_document_signature
The tool receives structured input, applies policy checks, calls your backend, and returns a constrained result. The agent should never receive a DigiLocker client secret, refresh token, internal database credentials, or unrestricted document archive.
A robust design separates four layers:
1. Agent layer: selects a tool and supplies user-approved parameters.
2. WebMCP tool layer: validates input, checks authorization, and enforces scope.
3. DigiLocker connector: handles OAuth, API requests, document retrieval, and verification.
4. Policy and audit layer: records consent, purpose, access decisions, and outcomes.
This separation is important because prompt instructions are not a security boundary. The server must enforce every permission independently of what the model requests.
Before You Start: DigiLocker Access and Compliance
DigiLocker access is not equivalent to scraping the public website. Production integrations should use officially supported APIs, partner onboarding processes, and documented authentication flows. Confirm the current DigiLocker integration requirements before implementation because endpoints, scopes, approval procedures, and data policies can change.
Prepare the following:
- A registered organisation and verified redirect URLs.
- A documented user-consent and purpose-limitation flow.
- OAuth credentials stored in a secrets manager.
- A privacy notice explaining what is accessed, why, and for how long.
- A retention and deletion policy for retrieved documents and extracted fields.
- Access controls for employees, services, tenants, and support personnel.
- An incident-response process for token leakage or unauthorised access.
For Indian deployments, assess obligations under the Digital Personal Data Protection Act, 2023, applicable rules and sector-specific requirements. If your workflow handles education, financial, employment, health, or identity data, additional contractual and regulatory controls may apply. Your legal and security teams should validate the final design rather than relying on a generic checklist.
Recommended Architecture
A production WebMCP tool should not call DigiLocker directly from a browser or expose raw documents to an LLM by default. Use a backend-for-frontend or tool gateway:
User + Agent
|
v
WebMCP Tool Gateway
- schema validation
- user/session binding
- consent check
- rate limiting
- output filtering
|
v
DigiLocker Connector
- OAuth token management
- official API client
- document retrieval
- signature/format validation
|
v
Encrypted storage or transient processingThe agent should first request authorisation. Your application redirects the user to DigiLocker through the approved OAuth process. After the user grants consent, your backend stores tokens securely and associates them with a user or tenant—not with the language model session alone.
Use short-lived access tokens where possible. Encrypt refresh tokens at rest, restrict decryption to the connector service, and never place tokens in prompts, tool outputs, logs, traces, analytics, or error messages.
Define Narrow, Typed Tools
Avoid a generic tool such as download_any_digilocker_file. It is difficult to govern and encourages excessive access. Design tools around a business purpose and return only the minimum fields needed.
For example, an onboarding product may need identity matching rather than a full document. A tool could accept a document reference and a field allowlist:
{
"document_id": "opaque-reference",
"fields": ["name", "date_of_birth"],
"purpose": "candidate_identity_verification"
}The server should validate that:
- The document belongs to the authenticated user or an authorised organisation.
- The requested fields are allowed for the stated purpose.
- The purpose is present in an active consent record.
- The document type is supported by the workflow.
- The request is within rate and frequency limits.
Do not allow arbitrary JSON paths, URLs, XPath expressions, or code snippets from the agent. Those features create opportunities for data exfiltration and parser abuse.
Example WebMCP Tool Contract
The exact WebMCP registration API depends on the framework you use. The important part is a stable name, description, JSON Schema input, authentication requirement, and constrained output.
const extractDigiLockerFields = {
name: "extract_digilocker_fields",
description:
"Extract approved fields from a user's consented DigiLocker document.",
inputSchema: {
type: "object",
additionalProperties: false,
required: ["document_id", "fields", "purpose"],
properties: {
document_id: {
type: "string",
minLength: 8,
maxLength: 200
},
fields: {
type: "array",
minItems: 1,
maxItems: 10,
uniqueItems: true,
items: {
type: "string",
enum: ["name", "date_of_birth", "document_number", "issuer", "issue_date"]
}
},
purpose: {
type: "string",
enum: ["identity_verification", "education_verification", "employment_onboarding"]
}
}
}
};The response should distinguish between extracted values, verification status, and uncertainty. A useful result might be:
{
"status": "verified",
"document_type": "education_certificate",
"fields": {
"name": {"value": "Asha Rao", "confidence": 0.99},
"issue_date": {"value": "2024-07-15", "confidence": 0.98}
},
"source": {
"issuer": "authorised-digilocker-source",
"retrieved_at": "2026-09-03T10:30:00Z"
},
"warnings": []
}Do not claim that a document is authentic solely because an OCR model found plausible text. Separate document retrieval, cryptographic or issuer verification, and field extraction. If signature verification is unavailable, return an explicit status such as not_verified.
Implement the Consent and OAuth Flow
A safe flow looks like this:
1. The user starts a specific workflow, such as education verification.
2. Your application displays the purpose, requested document category, fields, retention period, and revocation method.
3. The user is redirected to DigiLocker using the approved OAuth authorisation flow.
4. DigiLocker authenticates the user and records the applicable consent.
5. Your callback validates the state parameter and exchanges the authorisation code server-side.
6. Your backend stores tokens in an encrypted, access-controlled token store.
7. The agent can invoke only tools permitted by the resulting consent.
8. The user can revoke access, after which cached data and tokens are deleted or disabled according to policy.
Use PKCE for public clients, exact redirect URI matching, CSRF-resistant state values, and server-side code exchange. Bind the OAuth transaction to the authenticated application user and tenant. Never accept a user identifier supplied solely by the model.
Illustrative callback logic:
async function oauthCallback(request: Request) {
const { code, state } = parseQuery(request.url);
const transaction = await oauthStateStore.consume(state);
if (!transaction || transaction.expiresAt < Date.now()) {
throw new Error("Invalid or expired OAuth state");
}
const tokens = await digilocker.exchangeCode({
code,
redirectUri: transaction.redirectUri,
codeVerifier: transaction.codeVerifier
});
await tokenVault.save({
subjectId: transaction.userId,
tenantId: transaction.tenantId,
encryptedTokens: await encrypt(tokens)
});
return redirectToApplication("/verification/connected");
}In production, use the official DigiLocker documentation for endpoint names, scopes, certificate requirements, and response formats rather than copying undocumented examples.
Build the Tool Handler with Server-Side Policy Checks
A handler should treat every agent request as untrusted input. Validate the schema first, then apply identity, consent, ownership, purpose, and field-level policies.
async function handleExtract(input: unknown, context: ToolContext) {
const request = extractSchema.parse(input);
const subject = await identity.requireUser(context);
await policy.requireConsent({
subjectId: subject.id,
purpose: request.purpose,
documentId: request.document_id,
fields: request.fields
});
await rateLimiter.check(`extract:${subject.id}`);
const token = await tokenVault.get(subject.id);
const document = await digilocker.getDocument(token, request.document_id);
const verification = await verifyDocument(document);
const fields = await extractAllowlistedFields(document, request.fields);
await audit.log({
actor: subject.id,
action: "extract_digilocker_fields",
purpose: request.purpose,
documentIdHash: sha256(request.document_id),
fields: request.fields,
verificationStatus: verification.status
});
return redactAndFormat({ verification, fields });
}Notice that the audit record hashes the document identifier and records requested field names, not the document contents. Logs should be useful for investigations without becoming a second sensitive-data repository.
Handle Documents, OCR, and Structured Extraction Safely
DigiLocker records may be returned as structured data, PDFs, XML, or other formats. Prefer issuer-provided structured fields over OCR. If OCR is necessary:
- Process files in an isolated worker with resource limits.
- Enforce maximum file size, page count, and decompression limits.
- Treat extracted text as untrusted content.
- Strip scripts, embedded actions, and active content before rendering.
- Use allowlisted field mappings rather than free-form model extraction.
- Preserve raw evidence only when necessary and for a defined retention period.
- Return uncertainty when text is missing, ambiguous, or inconsistent.
Prompt injection can exist inside documents. A PDF or credential may contain text such as “ignore previous instructions.” The extraction pipeline must treat document content as data, never as instructions. Instruct the model, if used, to extract only from designated fields and ignore all embedded commands.
For high-impact decisions, do not let an LLM make the final determination. Use deterministic checks for date formats, identifier patterns, issuer match, duplicate records, and name normalisation. Route conflicts to a human review queue.
Security Controls You Should Not Skip
At minimum, implement:
- Authentication: bind every tool call to a real user, service identity, and tenant.
- Authorisation: enforce document ownership and purpose-based field access.
- Least privilege: separate read metadata, retrieve document, and extract fields permissions.
- Secrets management: use a cloud KMS or secrets manager; never environment variables in shared logs.
- Transport security: TLS, certificate validation, and secure internal service communication.
- Rate limits: per user, tenant, document, IP, and tool operation.
- Replay protection: idempotency keys and short-lived tool invocation tokens.
- Output controls: redact unrequested fields and cap response size.
- Auditability: record consent version, purpose, actor, timestamp, result status, and policy decisions.
- Monitoring: alert on unusual volume, repeated failures, bulk enumeration, and access after revocation.
Do not expose sequential document IDs if they enable enumeration. Use opaque references and verify ownership on every lookup.
Testing Strategy for a Production Tool
Test the integration at four levels.
Contract tests
Validate JSON Schema rejection, unknown fields, oversized arrays, invalid purposes, and malformed identifiers. Confirm that the tool description accurately reflects actual behaviour.
Security tests
Attempt token disclosure through error messages, prompts, logs, traces, and model responses. Test cross-tenant document access, replayed OAuth callbacks, CSRF, SSRF through document URLs, path traversal, malicious PDFs, and prompt injection.
Data-quality tests
Use fixture documents with alternate name formats, Indian date formats, transliteration, missing fields, duplicate names, low-quality scans, and conflicting metadata. Verify that the system returns uncertainty instead of inventing values.
Operational tests
Test DigiLocker timeouts, revoked consent, expired tokens, rate limits, partial responses, duplicate callbacks, and connector outages. The agent should receive a clear, non-sensitive error such as consent_required, temporarily_unavailable, or manual_review_required.
Common Mistakes to Avoid
- Scraping the DigiLocker web interface instead of using an authorised integration.
- Asking the agent to collect passwords, OTPs, or access tokens.
- Returning an entire document when two fields are sufficient.
- Treating OCR confidence as proof of authenticity.
- Allowing the model to select arbitrary document URLs or fields.
- Storing raw documents indefinitely “for debugging.”
- Logging tokens, full identifiers, or complete extracted records.
- Assuming a user’s consent for one purpose covers unrelated uses.
- Making irreversible eligibility decisions solely from an LLM output.
- Failing open when the consent service or policy engine is unavailable.
A Practical Launch Checklist
Before releasing your WebMCP DigiLocker tool, confirm:
- [ ] Official API access and integration terms are approved.
- [ ] OAuth redirect, state, PKCE, token storage, and revocation work correctly.
- [ ] Tool schemas reject unknown and excessive inputs.
- [ ] Every request is bound to an authenticated subject and tenant.
- [ ] Purpose limitation and field-level consent are enforced server-side.
- [ ] Document verification is separate from OCR and LLM extraction.
- [ ] Raw files, tokens, and sensitive logs have defined retention controls.
- [ ] Audit events are tamper-resistant and privacy-conscious.
- [ ] Abuse, injection, malware, and cross-tenant tests are complete.
- [ ] Users can see, revoke, and understand access to their data.
- [ ] Human review exists for ambiguous or high-impact results.
FAQ
Can an AI agent log in to DigiLocker for the user?
No. The agent should not handle passwords, OTPs, or credentials. Send the user through an approved OAuth and consent flow, then let the backend use securely stored tokens.
Should the tool return the complete DigiLocker PDF?
Usually not. Return only the minimum verified fields required for the stated purpose. Provide the full document only when there is a clear, authorised business need and suitable retention controls.
Can I use OCR for DigiLocker documents?
Yes, when necessary, but OCR is an extraction technique—not proof of authenticity. Prefer structured issuer data and apply independent verification and deterministic validation.
Is WebMCP itself a security layer?
No. WebMCP defines how an agent discovers and invokes tools. Authentication, authorisation, consent, data minimisation, validation, and auditing must be implemented by your application and backend.
What should happen when consent is revoked?
Block further access immediately, invalidate or disable relevant tokens, stop scheduled retrievals, and delete or de-identify cached data according to your documented legal and operational retention policy.
Apply for AI Grants India
Building a privacy-preserving agent, verified-document workflow, or India-focused AI infrastructure product? Apply to AI Grants India for support, visibility, and opportunities for Indian AI founders.