
The Model Context Protocol (MCP) defines a standardized interface for AI models to interact with external tools, resources, and context providers. This guide details the construction of a custom MCP server using TypeScript and the official @modelcontextprotocol/sdk, focusing on robust architecture, schema validation, transport mechanisms, and cloud deployment.
Configure stdio & SSE servers with Claude, Cursor & Python export
Configure and validate Model Context Protocol (MCP) servers with stdio and SSE transports. Export ready-to-run configurations for Claude Desktop, Claude Code CLI, Cursor, and TypeScript/Python SDKs.
An MCP server fundamentally processes incoming MCPRequest objects and generates MCPResponse objects. The server's responsibilities include:
MCPRequest payloads against defined schemas.MCPResponse objects.We will implement a server that supports both stdio and Server-Sent Events (SSE) transports, leveraging Zod for schema validation and Google Cloud Run for deployment.
Initialize a new TypeScript project:
mkdir mcp-server-ts
cd mcp-server-ts
npm init -y
npm install typescript @types/node ts-node zod @modelcontextprotocol/sdk express @types/express
npm install --save-dev @types/ws ws
npx tsc --init
Configure tsconfig.json for strictness and ESNext modules:
// tsconfig.json
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"rootDir": "./src",
"outDir": "./dist",
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"strict": true,
"skipLibCheck": true
},
"include": ["src/**/*.ts"],
"exclude": ["node_modules"]
}
In the official Model Context Protocol TypeScript SDK, request schemas are exported directly from @modelcontextprotocol/sdk/types.js, and tool input schemas are validated cleanly using standard zod.
// src/schemas.ts
import { z } from 'zod';
export const SearchToolInputSchema = z.object({
query: z.string().describe("The search query to execute."),
limit: z.number().int().min(1).max(20).optional().default(5).describe("Max results to return."),
});
export type SearchToolInput = z.infer<typeof SearchToolInputSchema>;
@modelcontextprotocol/sdkMCP servers expose capabilities through tools, resources, and prompts. In the official SDK, you instantiate a Server and register typed request handlers:
// src/server.ts
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
import {
CallToolRequestSchema,
ListToolsRequestSchema,
ListResourcesRequestSchema,
ReadResourceRequestSchema,
ListPromptsRequestSchema,
GetPromptRequestSchema,
McpError,
ErrorCode,
} from '@modelcontextprotocol/sdk/types.js';
import { SearchToolInputSchema } from './schemas.js';
export function createMcpServer() {
const server = new Server(
{
name: 'production-mcp-server',
version: '1.0.0',
},
{
capabilities: {
tools: {},
resources: {},
prompts: {},
},
}
);
// --- 1. Tools: List and Call Handlers ---
server.setRequestHandler(ListToolsRequestSchema, async () => {
return {
tools: [
{
name: 'search',
description: 'A tool for searching internal knowledge bases.',
inputSchema: {
type: 'object',
properties: {
query: { type: 'string', description: 'The search query to execute.' },
limit: { type: 'number', description: 'Max results to return (1-20).' },
},
required: ['query'],
},
},
],
};
});
server.setRequestHandler(CallToolRequestSchema, async (request) => {
if (request.params.name === 'search') {
const parsed = SearchToolInputSchema.safeParse(request.params.arguments);
if (!parsed.success) {
throw new McpError(ErrorCode.InvalidParams, `Invalid parameters: ${parsed.error.message}`);
}
const { query, limit = 5 } = parsed.data;
console.log(`Executing search for query: "${query}" (limit: ${limit})`);
// Simulated database / search engine query
const results = [
`Article 1: Architecture patterns for "${query}"`,
`Article 2: Production gotchas when scaling "${query}"`,
].slice(0, limit);
return {
content: [
{
type: 'text',
text: JSON.stringify({ query, count: results.length, results }),
},
],
};
}
throw new McpError(ErrorCode.MethodNotFound, `Unknown tool: ${request.params.name}`);
});
// --- 2. Resources: List and Read Handlers ---
server.setRequestHandler(ListResourcesRequestSchema, async () => {
return {
resources: [
{
uri: 'docs://system-architecture',
name: 'System Architecture Specification',
mimeType: 'text/markdown',
description: 'Living architecture decision records (ADR).',
},
],
};
});
server.setRequestHandler(ReadResourceRequestSchema, async (request) => {
if (request.params.uri === 'docs://system-architecture') {
return {
contents: [
{
uri: request.params.uri,
mimeType: 'text/markdown',
text: '# Core Architecture\n\nAll services communicate via gRPC with mTLS enabled.',
},
],
};
}
throw new McpError(ErrorCode.InvalidRequest, `Resource not found: ${request.params.uri}`);
});
// --- 3. Prompts: List and Get Handlers ---
server.setRequestHandler(ListPromptsRequestSchema, async () => {
return {
prompts: [
{
name: 'code-review',
description: 'Review a diff against production security guidelines.',
arguments: [
{ name: 'diff', description: 'The git diff string', required: true },
],
},
],
};
});
server.setRequestHandler(GetPromptRequestSchema, async (request) => {
if (request.params.name === 'code-review') {
const diff = request.params.arguments?.diff || '';
return {
messages: [
{
role: 'user',
content: {
type: 'text',
text: `Please review the following pull request diff for security vulnerabilities, edge-case leaks, and performance regressions:\n\n\`\`\`diff\n${diff}\n\`\`\``,
},
},
],
};
}
throw new McpError(ErrorCode.InvalidRequest, `Prompt not found: ${request.params.name}`);
});
return server;
}
MCP supports multiple transports. We will implement both standard stdio (for local development, Claude Desktop, and CLI runners) and SSE (for HTTP-based streaming deployments on Google Cloud Run or AWS ECS).
stdioServer.ts)The stdio transport runs over process.stdin and process.stdout using JSON-RPC 2.0 frames. The official SDK abstracts all stream buffering and framing via StdioServerTransport:
// src/stdioServer.ts
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
import { createMcpServer } from './server.js';
export async function startStdioServer() {
const server = createMcpServer();
const transport = new StdioServerTransport();
await server.connect(transport);
console.error('MCP Stdio Server running and ready for client connections.');
}
if (process.env.TRANSPORT !== 'sse') {
startStdioServer().catch((err) => {
console.error('Fatal stdio server error:', err);
process.exit(1);
});
}
sseServer.ts)For remote deployments (e.g. Docker on Cloud Run), SSE provides persistent unidirectional streaming over HTTP while client commands POST back to an endpoint. The SDK provides SSEServerTransport:
// src/sseServer.ts
import express from 'express';
import { SSEServerTransport } from '@modelcontextprotocol/sdk/server/sse.js';
import { createMcpServer } from './server.js';
const app = express();
const PORT = process.env.PORT || 8080;
// Maintain active transport sessions by session ID
const transports: Record<string, SSEServerTransport> = {};
// SSE connection endpoint
app.get('/sse', async (req, res) => {
console.log('Client connected via SSE');
const transport = new SSEServerTransport('/messages', res);
const server = createMcpServer();
transports[transport.sessionId] = transport;
res.on('close', () => {
console.log(`SSE client closed connection: ${transport.sessionId}`);
delete transports[transport.sessionId];
});
await server.connect(transport);
});
// HTTP POST endpoint for client JSON-RPC messages
app.post('/messages', async (req, res) => {
const sessionId = req.query.sessionId as string;
const transport = transports[sessionId];
if (!transport) {
res.status(400).send(`Active session ${sessionId} not found`);
return;
}
await transport.handlePostMessage(req, res);
});
// Health check endpoint for Cloud Run
app.get('/healthz', (req, res) => {
res.status(200).send('OK');
});
export function startSseServer() {
app.listen(PORT, () => {
console.log(`MCP SSE Server listening on port ${PORT}`);
});
}
if (process.env.TRANSPORT === 'sse') {
startSseServer();
}
A single entry point to choose the server type based on environment variables.
// src/index.ts
import { startStdioServer } from './stdioServer';
import { startSseServer } from './sseServer';
const SERVER_TYPE = process.env.MCP_SERVER_TYPE || 'sse'; // Default to SSE
if (SERVER_TYPE === 'stdio') {
startStdioServer();
} else if (SERVER_TYPE === 'sse') {
startSseServer();
} else {
console.error(`Unknown MCP_SERVER_TYPE: ${SERVER_TYPE}. Must be 'stdio' or 'sse'.`);
process.exit(1);
}
| Feature | stdio | SSE (HTTP) |
|---|---|---|
| Protocol | Custom length-prefixed binary/text | HTTP/1.1, text-based |
| Connection | Persistent (stdin/stdout) | Persistent (single request/response stream) |
| Streaming | Bidirectional (via separate pipes) | Unidirectional (server to client) |
| Overhead | Minimal | HTTP headers, event framing |
| Complexity | Low (SDK handles framing) | Moderate (HTTP server, headers, event format) |
| Use Case | CLI tools, local agents, container-internal | Web clients, cloud functions, external services |
| Authentication | OS-level permissions | HTTP headers (Bearer tokens, API keys) |
| Error Handling | Application-level messages | HTTP status codes, application-level events |
| Scalability | Single process | Horizontally scalable (load balancers) |
Containerize the application for consistent deployment.
# Dockerfile
# Use a slim Node.js image for smaller size
FROM node:20-slim AS builder
WORKDIR /app
# Copy package.json and package-lock.json first to leverage Docker cache
COPY package*.json ./
RUN npm install --omit=dev
# Copy source code
COPY . .
# Build TypeScript code
RUN npm run build
# --- Production Stage ---
FROM node:20-slim
WORKDIR /app
# Copy only necessary files from the builder stage
COPY --from=builder /app/package*.json ./
COPY --from=builder /app/node_modules ./node_modules
COPY --from=builder /app/dist ./dist
# Expose the port for the SSE server
EXPOSE 8080
# Set environment variable for SSE server type
ENV MCP_SERVER_TYPE=sse
# Command to run the SSE server
CMD ["node", "dist/index.js"]
Build the Docker image:
docker build -t mcp-server-ts .
Run locally (SSE):
docker run -p 8080:8080 mcp-server-ts
Test with curl:
curl -X POST -H "Content-Type: application/json" \
-d '{
"tool_calls": [
{ "call_id": "call-1", "name": "search", "input": { "query": "latest AI research" } }
],
"resource_fetches": [
{ "fetch_id": "fetch-1", "name": "documentation", "id": "mcp-overview" }
],
"prompt_template_renders": [
{ "render_id": "render-1", "name": "summary", "variables": { "document": "This is a very long document about the history of computing.", "length": "brief" } }
]
}' \
http://localhost:8080/mcp/stream
Expected output (streamed events):
event: request_received
data: {"request_id":"<uuid>"}
event: response
data: {"request_id":"<uuid>","tool_results":[{"call_id":"call-1","output":{"results":["Result 1 for \"latest AI research\"","Result 2 for \"latest AI research\""]}}],"resource_data":[{"fetch_id":"fetch-1","data":"The Model Context Protocol (MCP) standardizes AI model interaction with external systems."}],"prompt_template_outputs":[{"render_id":"render-1","output":"Here is a brief summary of the document: \"This is a very long document about the history of compu...\""}]}
Google Cloud Run is an ideal serverless platform for containerized applications, offering automatic scaling and pay-per-use billing.
gcloud CLI installed and authenticated.Build and Push Docker Image to Google Container Registry (GCR) or Artifact Registry:
# For GCR (older, but widely used)
docker tag mcp-server-ts gcr.io/<YOUR_PROJECT_ID>/mcp-server-ts:latest
docker push gcr.io/<YOUR_PROJECT_ID>/mcp-server-ts:latest
# For Artifact Registry (recommended)
# Enable Artifact Registry API: gcloud services enable artifactregistry.googleapis.com
# Create a repository: gcloud artifacts repositories create mcp-repo --repository-format=docker --location=us-central1 --description="MCP Docker repository"
docker tag mcp-server-ts us-central1-docker.pkg.dev/<YOUR_PROJECT_ID>/mcp-repo/mcp-server-ts:latest
docker push us-central1-docker.pkg.dev/<YOUR_PROJECT_ID>/mcp-repo/mcp-server-ts:latest
Deploy to Cloud Run:
gcloud run deploy mcp-server-ts \
--image gcr.io/<YOUR_PROJECT_ID>/mcp-server-ts:latest \
--platform managed \
--region us-central1 \
--allow-unauthenticated \
--port 8080 \
--min-instances 0 \
--max-instances 10 \
--memory 512Mi \
--cpu 1 \
--set-env-vars MCP_SERVER_TYPE=sse \
--project <YOUR_PROJECT_ID>
--allow-unauthenticated: For public access. For production, consider --no-allow-unauthenticated and use IAM.--port 8080: Matches the EXPOSE in Dockerfile. Cloud Run automatically routes traffic to this port.--set-env-vars MCP_SERVER_TYPE=sse: Ensures the SSE server starts.IAM Authentication (Recommended for Production):
If --no-allow-unauthenticated is used, clients must authenticate. For service-to-service communication within GCP, use service accounts.
Client Service Account: Create a service account for the client (e.g., an AI model service).
Grant Invoker Role: Grant the roles/run.invoker role to the client service account on your Cloud Run service.
gcloud run services add-iam-policy-binding mcp-server-ts \
--member="serviceAccount:<CLIENT_SERVICE_ACCOUNT_EMAIL>" \
--role="roles/run.invoker" \
--region us-central1 \
--platform managed
Client-side Authentication: When making requests from a GCP service, the gcloud client libraries or curl with gcloud auth print-identity-token can automatically handle authentication.
# Example curl with authenticated token
SERVICE_URL=$(gcloud run services describe mcp-server-ts --platform managed --region us-central1 --format 'value(status.url)')
TOKEN=$(gcloud auth print-identity-token)
curl -X POST -H "Content-Type: application/json" \
-H "Authorization: Bearer ${TOKEN}" \
-d '{
"tool_calls": [
{ "call_id": "call-1", "name": "search", "input": { "query": "cloud run deployment" } }
]
}' \
"${SERVICE_URL}/mcp/stream"
403 Forbidden on Cloud Run:
--no-allow-unauthenticated was used during deployment, but the client is not providing a valid Authorization header with a Cloud Run invoker token.roles/run.invoker on the Cloud Run service.gcloud auth print-identity-token or Google Auth Libraries).--allow-unauthenticated.500 Internal Server Error / Container instance crashed:
PORT environment variable, unhandled exceptions, or out-of-memory errors.gcloud run services logs read mcp-server-ts --limit 100). Look for Error: listen EADDRINUSE (port conflict, unlikely in Cloud Run), UnhandledPromiseRejectionWarning, or Memory limit exceeded.process.env.PORT (Cloud Run injects this). Our sseServer.ts correctly uses process.env.PORT || 8080.--memory) or CPU (--cpu) if logs indicate resource exhaustion.try...catch blocks around asynchronous operations.400 Bad Request from /mcp/stream:
MCPRequestSchema. This often happens due to missing required fields or incorrect data types.MCPRequestSchema (and any custom schemas).catch block for MCPRequestSchema.parse to output Zod validation errors.import { ZodError } from 'zod';
// ... inside try/catch for MCPRequestSchema.parse
} catch (error: any) {
if (error instanceof ZodError) {
console.error("Zod validation error:", JSON.stringify(error.errors, null, 2));
// ... send detailed error response
} else {
console.error("Non-Zod error:", error);
}
}
Slow Responses / Timeouts:
--timeout).SSE Connection Dropping Prematurely:
X-Accel-Buffering: no header is set (our setSSEHeaders function does this).: comment\n\n) if the server might be idle for extended periods between actual data events.When designing an MCP server for high-throughput, low-latency AI model interactions, which transport layer choice, between stdio and SSE, presents a critical trade-off for real-world production environments, and why?
A1:
src/schemas.ts. Extend ToolDefinitionSchema or ResourceDefinitionSchema.src/handlers.ts that takes the parsed input and returns the output.toolExecutors or resourceFetchers map in src/handlers.ts.ToolDefinition or ResourceDefinition to the serverCapabilities array in src/handlers.ts so clients can discover it.A2: While MCP itself is transport-agnostic, the @modelcontextprotocol/sdk currently provides specific helpers for stdio and SSE. WebSockets would require a custom implementation of the transport layer. You would need to:
ws library with Express).type and payload fields) over the WebSocket.handleMCPRequest to process incoming WebSocket messages and send responses back over the same connection.
This is feasible but requires more manual work than the provided SSE/stdio examples.A3:
<YOUR_PROJECT_ID>@appspot.gserviceaccount.com by default) the Secret Manager Secret Accessor role on the specific secrets.gcloud run deploy mcp-server-ts ... \
--set-secrets=EXTERNAL_API_KEY=EXTERNAL_API_KEY:latest \
...
process.env.EXTERNAL_API_KEY.A4: For long-running operations (e.g., complex ML model inference, large data processing), direct synchronous execution within the MCP request is not suitable. Consider these patterns:
MCPResponse indicating the task has been accepted, possibly with a task_id.task_id to check for completion and retrieve results.A5: You can pipe JSON data to its stdin.
Compile the server: npm run build
Prepare a request file:
// request.json
{
"request_id": "test-stdio-1",
"tool_calls": [
{ "call_id": "call-stdio-1", "name": "search", "input": { "query": "stdio transport" } }
]
}
Test your server interactively with the official MCP Inspector:
# Launch the official visual MCP Inspector
npx @modelcontextprotocol/inspector node dist/stdioServer.js
This opens a browser interface at http://localhost:5173 where you can inspect capabilities, list tools, and execute test payloads with zero manual JSON formatting.
Alternatively, to test raw stdio manually with length-prefixed framing:
# In another terminal:
# Get the length of the JSON string
# echo '{"request_id":"test-stdio-1","tool_calls":[{"call_id":"call-stdio-1","name":"search","input":{"query":"stdio transport"}}]}' | wc -c
# (Let's say it's 123 bytes)
# Then send:
echo -n -e '\x00\x00\x00\x7B{"request_id":"test-stdio-1","tool_calls":[{"call_id":"call-stdio-1","name":"search","input":{"query":"stdio transport"}}]}' | node dist/index.js
# Note: The \x00\x00\x00\x7B represents the 4-byte big-endian message length prefix (0x7B = 123 bytes).
Clean AI CLI logs, build cron expressions, decode JWTs, and calculate chmod permissions offline.

Step-by-step implementation of a custom Model Context Protocol (MCP) client in TypeScript: managing stdio/SSE transports, dynamic tool discovery, and multi-server LLM sessions.
Read more
Architecting, securing, and deploying production remote Model Context Protocol (MCP) servers with Streamable HTTP, DNS rebinding mitigation, OAuth 2.1 bearer tokens, and FastAPI.
Read more
How to build and host production Model Context Protocol (MCP) servers on Cloudflare Workers using SSE transports, KV token storage, and Durable Objects.
Read more