MCP Server Implementation
Relevant source files
The following files were used as context for generating this wiki page:
The Model Context Protocol (MCP) server implementation in e-zer0 provides a secure, standardized bridge between AI agents and email services like Gmail and Outlook. It abstracts provider-specific APIs into a unified set of tools that allow agents to read, search, and manage emails, calendars, and tasks.
The implementation relies on the @modelcontextprotocol/sdk and runs within Cloudflare Workers, using D1 for database storage and Web Standard Streamable HTTP for transport.
Sources: AGENTS.md:1-12, src/mcp/server.ts:1-10
Architecture and Data Flow
The MCP implementation follows a layered architecture. The Hono application handles routing and authentication, while a dedicated transport layer manages communication with MCP clients. The server logic itself maps high-level tool definitions to specific internal functions.
Request Flow
- An AI agent sends an HTTP POST request to the
/mcpendpoint. - The system validates the request using a JWT Bearer token and checks the rate limit.
- A fresh
McpServerinstance is created for the session. - The
WebStandardStreamableHTTPServerTransporthandles the RPC lifecycle. - Tool executions are logged to the audit trail in the D1 database.
The following diagram illustrates the lifecycle of an MCP request:
Authentication and Security
The MCP server implements a custom OAuth 2.0 flow for client authorization. AI agents must obtain a short-lived JWT to access the MCP endpoints.
- Token Issuance: The
/mcp/tokenendpoint supportsclient_credentials,authorization_code, andrefresh_tokengrants. - JWT Security: Tokens are signed using HMAC-SHA256 with a secret stored in Cloudflare Workers secrets.
- Rate Limiting: The server uses Cloudflare KV to track and limit requests per IP and Client ID to prevent brute-force attacks.
- Audit Logging: Every tool execution is recorded in the
audit_logstable, capturing the client identity, action, target, and success status.
| Component | Logic Reference | Description |
|---|---|---|
| JWT Sign/Verify | signJwt, verifyJwt | Compact HMAC-SHA256 implementation using Web Crypto API. |
| Token Endpoint | /mcp/token | Validates client credentials and issues access/refresh tokens. |
| Rate Limiter | checkRateLimit | Prevents abuse using RATE_LIMITER KV binding. |
| Audit Trail | logAudit | Mandatory logging for all AI agent actions. |
Sources: src/routes/mcp.ts:67-180, src/types.ts:108-119, AGENTS.md:65-71
MCP Tool Definition
Tools are exposed via server.tool(...) in src/mcp/server.ts. Each tool includes a name, description, and a Zod schema for input validation. Tools are categorized by their functionality and provide hints for agents regarding their destructive nature.
Tool Categories
Email Management
Tools like get_emails, manage_email, and organize_email provide a unified interface for Gmail and Outlook.
server.tool(
'manage_email',
'Perform an action on a specific email (archive, delete, mark as read/unread)',
{
account_id: z.number().describe('The ID of the email account'),
message_id: z.string().describe('The ID of the email message'),
action: z.enum(['archive', 'delete', 'mark_read', 'mark_unread']).describe('The action to perform'),
},
{ readOnlyHint: false, destructiveHint: true, openWorldHint: false },
// ... implementation
);
Sources: src/mcp/server.ts:327-340
Calendar and Tasks
Read-only calendar access is separate from mailbox grants. Agents can list calendars and fetch events, but cannot create or modify them. Task management supports both Google Tasks and Microsoft To Do.
Sources: src/mcp/server.ts:245-282, README.md:95-120
Summary of Key Tools
| Tool Name | Operation Type | Purpose |
|---|---|---|
read_recent_emails | Read-only | Fetches the latest messages from an account. |
search_email_page | Read-only | Paginated searching using native provider queries. |
draft_email_reply | Write (Draft) | Creates a reply draft (does NOT send). |
get_calendar_events | Read-only | Fetches events overlapping a specific date range. |
create_task | Write | Adds a new task to a specific task list. |
Sources: src/mcp/server.ts:122-635
Transport Layer
The server uses the WebStandardStreamableHTTPServerTransport from the MCP SDK. This transport is optimized for Cloudflare Workers as it utilizes native Request, Response, and ReadableStream objects.
The transport implementation in src/routes/mcp.ts includes an observation layer that traces signals without logging sensitive payloads. It manages:
mcp_transport_started: Logs when a request begins.incoming_request_aborted: Traces when the client cancels the underlying HTTP request.mcp_response_stream_cancelled: Traces when the response stream is closed early.
Sources: src/routes/mcp.ts:18-65, src/routes/mcp.ts:223-231
Data Structures
The system uses the following core types to manage MCP state and interactions:
- McpClient: Represents a registered AI agent, including its
client_idand hashed secret. - McpClientAccount: Maps authorized clients to specific email accounts.
- AuditLog: Stores the history of all tool executions.
export interface McpClient {
id: number;
name: string;
client_id: string;
secret_hash: string;
salt: string;
is_active: number;
last_used_at: string | null;
}
Sources: src/types.ts:60-72
Conclusion
The MCP Server implementation serves as the secure interface for AI interactions. By combining a standardized protocol with unified email abstractions, strict audit logging, and Cloudflare's edge security, it enables agents to manage communication data while maintaining user control and privacy.