Cookbook MCP Postmessage
Browser-ready Model Context Protocol (MCP) SDK with PostMessage transport for client and server implementations
Ask AI about Cookbook MCP Postmessage
Powered by Claude Β· Grounded in docs
I know everything about Cookbook MCP Postmessage. Ask me about installation, configuration, usage, or troubleshooting.
0/500
Reviews
Documentation
MCP PostMessage Transport
A secure PostMessage transport implementation for the Model Context Protocol (MCP), enabling MCP communication between browser contexts (iframes, browser extensions, web workers, etc.).
Overview
This library provides a 1:1 interface mapping with the official MCP specification from Anthropic, using PostMessage as the transport layer. It's designed for scenarios where traditional MCP transports (stdio, HTTP) aren't available or suitable.
Features
- Full MCP Compliance: Implements the complete MCP specification
- Secure Communication: Built-in origin validation, rate limiting, and session management
- Browser-Native: Works with iframes, browser extensions, and web workers
- TypeScript Support: Full type definitions for the MCP protocol
- Zero Dependencies: Pure TypeScript implementation
Installation
npm install mcp-postmessage
Quick Start
Client Setup
import { MCPClient, SecurePostMessageTransport } from 'mcp-postmessage';
// Create a secure transport
const transport = new SecurePostMessageTransport(
targetWindow, // e.g., iframe.contentWindow
'https://trusted-origin.com',
undefined, // auto-generate session ID
{
allowedOrigins: ['https://trusted-origin.com'],
validateSession: true,
maxMessageSize: 1024 * 512 // 512KB
}
);
// Create MCP client
const client = new MCPClient({
name: 'my-client',
version: '1.0.0',
transport
});
// Connect and use
await client.connect();
// List available tools
const tools = await client.listTools();
// Call a tool
const result = await client.callTool('calculator', {
operation: 'add',
a: 5,
b: 3
});
Server Setup
import { MCPServer, SecurePostMessageTransport } from 'mcp-postmessage';
// Create server
const server = new MCPServer({
name: 'my-server',
version: '1.0.0',
capabilities: {
tools: {},
resources: { subscribe: true },
prompts: {}
}
});
// Register a tool
server.registerTool(
{
name: 'calculator',
description: 'Perform calculations',
inputSchema: {
type: 'object',
properties: {
operation: { type: 'string', enum: ['add', 'subtract'] },
a: { type: 'number' },
b: { type: 'number' }
},
required: ['operation', 'a', 'b']
}
},
async (args) => {
const result = args.operation === 'add' ? args.a + args.b : args.a - args.b;
return {
content: [{
type: 'text',
text: `Result: ${result}`
}]
};
}
);
// Start server
await server.start();
Security Features
The SecurePostMessageTransport includes:
- Origin Validation: Whitelist allowed origins
- Session Management: Secure session ID generation and validation
- Rate Limiting: Prevent abuse with configurable limits
- Message Size Limits: Prevent memory exhaustion
- Request Tracking: Limit concurrent pending requests
- Error Sanitization: Prevent information leakage
Examples
Browser Extension
See examples/browser-extension/ for a complete Chrome extension implementation using MCP for content script β background script communication.
IFrame Communication
See examples/iframe-communication/ for a working example of parent window β iframe MCP communication.
API Reference
Transport
PostMessageTransport: Basic PostMessage transport implementationSecurePostMessageTransport: Enhanced transport with security featuresBidirectionalPostMessageTransport: For bidirectional communication scenarios
Client
MCPClient: Full MCP client implementationconnect(): Initialize connectionlistTools(): List available toolscallTool(): Execute a toollistResources(): List available resourcesreadResource(): Read resource contentsubscribeResource(): Subscribe to resource updateslistPrompts(): List available promptsgetPrompt(): Get prompt template
Server
MCPServer: Full MCP server implementationstart(): Start the serverregisterTool(): Register a tool handlerregisterResource(): Register a resource handlerregisterPrompt(): Register a prompt handlernotifyResourceUpdated(): Notify subscribers of resource changes
Protocol Compliance
This implementation follows the MCP specification version 2025-03-26 and includes:
- JSON-RPC 2.0 message format
- Complete type definitions for all MCP types
- Full protocol method support
- Capability negotiation
- Change notifications
- Resource subscriptions
License
MIT
