Locionic
Blog
Projects
Dev ToolsCheatsheetsSeries & Guides
About MeFree Production KitContact
Send email to LocionicLocionic GitHub profileLocionic YouTube channel
© 2026Locionic• All rights reserved.
Dev Kits & Data•Tools•Tags•RSS•Privacy Policy•Terms
  1. Home
  2. Blog
  3. Building Custom MCP Servers with TypeScript: Complete Architecture & Deployment Guide
Wednesday, September 30, 2026•18 min read

Building Custom MCP Servers with TypeScript: Complete Architecture & Deployment Guide

Locionic
Locionic(@Locionic)
ai mcp typescript architecture
Building Custom MCP Servers with TypeScript: Complete Architecture & Deployment Guide

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.

Audio Briefing• Voice: Google Cloud Journey-F
0:00 / --:--
Interactive Dev Tool
100% Client-Side & Private

Model Context Protocol (MCP) Configurator

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.

MCP StandardClaude DesktopCursor RulesJSON Config
Launch Full ToolBrowse all 22 Dev Tools

Core MCP Server Architecture

An MCP server fundamentally processes incoming MCPRequest objects and generates MCPResponse objects. The server's responsibilities include:

  1. Transport Layer: Handling communication (e.g., HTTP, stdio).
  2. Request Deserialization & Validation: Parsing and validating MCPRequest payloads against defined schemas.
  3. Tool/Resource Orchestration: Executing requested tools or fetching specified resources.
  4. Response Serialization: Formatting 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.

Project Setup

Initialize a new TypeScript project:

bash
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:

json
// 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"]
}

Schema Definition and Tool Validation with Zod

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.

typescript
// 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>;

Implementing Tools, Resources, and Prompts with @modelcontextprotocol/sdk

MCP servers expose capabilities through tools, resources, and prompts. In the official SDK, you instantiate a Server and register typed request handlers:

typescript
// 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;
}

Transport Layer: Stdio vs. SSE

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).

Stdio Transport (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:

typescript
// 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);
  });
}

Server-Sent Events (SSE) Transport (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:

typescript
// 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();
}

Main Server Entry Point

A single entry point to choose the server type based on environment variables.

typescript
// 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);
}

Transport Comparison

FeaturestdioSSE (HTTP)
ProtocolCustom length-prefixed binary/textHTTP/1.1, text-based
ConnectionPersistent (stdin/stdout)Persistent (single request/response stream)
StreamingBidirectional (via separate pipes)Unidirectional (server to client)
OverheadMinimalHTTP headers, event framing
ComplexityLow (SDK handles framing)Moderate (HTTP server, headers, event format)
Use CaseCLI tools, local agents, container-internalWeb clients, cloud functions, external services
AuthenticationOS-level permissionsHTTP headers (Bearer tokens, API keys)
Error HandlingApplication-level messagesHTTP status codes, application-level events
ScalabilitySingle processHorizontally scalable (load balancers)

Containerization with Docker

Containerize the application for consistent deployment.

dockerfile
# 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:

bash
docker build -t mcp-server-ts .

Run locally (SSE):

bash
docker run -p 8080:8080 mcp-server-ts

Test with curl:

bash
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...\""}]}

Deployment to Google Cloud Run

Google Cloud Run is an ideal serverless platform for containerized applications, offering automatic scaling and pay-per-use billing.

Prerequisites

  • Google Cloud Project configured.
  • gcloud CLI installed and authenticated.
  • Cloud Run API enabled.

Deployment Steps

  1. Build and Push Docker Image to Google Container Registry (GCR) or Artifact Registry:

    bash
    # 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
    
  2. Deploy to Cloud Run:

    bash
    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.
  3. 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.

      bash
      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.

      bash
      # 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"
      

Production Gotchas & Troubleshooting

  1. 403 Forbidden on Cloud Run:

    • Cause: --no-allow-unauthenticated was used during deployment, but the client is not providing a valid Authorization header with a Cloud Run invoker token.
    • Fix:
      • Ensure the calling service account has roles/run.invoker on the Cloud Run service.
      • Verify the client is correctly generating and attaching an ID token (e.g., using gcloud auth print-identity-token or Google Auth Libraries).
      • If public access is intended, redeploy with --allow-unauthenticated.
  2. 500 Internal Server Error / Container instance crashed:

    • Cause: Application crash during startup or request processing. Common issues include incorrect PORT environment variable, unhandled exceptions, or out-of-memory errors.
    • Fix:
      • Check Cloud Run logs (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.
      • Ensure your application listens on process.env.PORT (Cloud Run injects this). Our sseServer.ts correctly uses process.env.PORT || 8080.
      • Increase memory (--memory) or CPU (--cpu) if logs indicate resource exhaustion.
      • Add more robust try...catch blocks around asynchronous operations.
  3. 400 Bad Request from /mcp/stream:

    • Cause: The incoming JSON payload does not conform to MCPRequestSchema. This often happens due to missing required fields or incorrect data types.
    • Fix:
      • Review the client's request body against MCPRequestSchema (and any custom schemas).
      • Add more detailed logging in the server's catch block for MCPRequestSchema.parse to output Zod validation errors.
      • Example:
        typescript
        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);
          }
        }
        
  4. Slow Responses / Timeouts:

    • Cause: Long-running tool executions, resource fetches, or prompt template renders. Cloud Run has a default request timeout (e.g., 5 minutes).
    • Fix:
      • Optimize handler logic.
      • Implement asynchronous patterns for very long tasks (e.g., offload to Cloud Tasks or Pub/Sub, and have the MCP server poll for results or receive webhooks).
      • Increase Cloud Run request timeout (--timeout).
      • Ensure external API calls have appropriate timeouts.
  5. SSE Connection Dropping Prematurely:

    • Cause: Proxies (like Nginx or Cloud Load Balancers) might buffer responses, preventing immediate streaming. Cloud Run itself handles SSE well, but intermediate proxies might interfere.
    • Fix:
      • Ensure X-Accel-Buffering: no header is set (our setSSEHeaders function does this).
      • Verify no other proxy in front of Cloud Run is buffering.
      • Keep-alive mechanisms: While SSE is inherently keep-alive, if the server is idle for too long, some network components might close the connection. Consider sending periodic "heartbeat" comments (: comment\n\n) if the server might be idle for extended periods between actual data events.

Test Your Knowledge

Interactive Quiz
Question 1 of 2

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?

You Might Also Like

  • Building Custom MCP Servers & Clients in TypeScript: Tools, Resources & Prompts Architecture
  • Building a Custom MCP Client: Connecting Any LLM to Multiple Model Context Protocol Servers
  • Building Production MCP Servers on Cloudflare Workers, KV & Durable Objects
  • Serverless Edge AI with Cloudflare Workers: D1, Vectorize & Streaming RAG Guide (2026)

Frequently Asked Questions

Q1: How do I add a new custom tool or resource to my MCP server?

A1:

  1. Define Schema: Create a Zod schema for the tool's input and output (or resource's ID and data) in src/schemas.ts. Extend ToolDefinitionSchema or ResourceDefinitionSchema.
  2. Implement Logic: Write an asynchronous function in src/handlers.ts that takes the parsed input and returns the output.
  3. Register Executor: Add your new function to the toolExecutors or resourceFetchers map in src/handlers.ts.
  4. Update Capabilities: Add your ToolDefinition or ResourceDefinition to the serverCapabilities array in src/handlers.ts so clients can discover it.
  5. Rebuild and Deploy: Rebuild your Docker image and redeploy to Cloud Run.

Q2: Can I use WebSockets instead of SSE for bidirectional streaming?

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:

  1. Set up a WebSocket server (e.g., using ws library with Express).
  2. Implement message framing (e.g., JSON messages with type and payload fields) over the WebSocket.
  3. Adapt 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.

Q3: How do I manage secrets (e.g., API keys for external tools) in a Cloud Run MCP server?

A3:

  1. Cloud Secret Manager: Store secrets in Google Cloud Secret Manager.
  2. Grant Access: Grant the Cloud Run service account (<YOUR_PROJECT_ID>@appspot.gserviceaccount.com by default) the Secret Manager Secret Accessor role on the specific secrets.
  3. Mount as Environment Variables: Configure Cloud Run to mount secrets as environment variables during deployment:
    bash
    gcloud run deploy mcp-server-ts ... \
      --set-secrets=EXTERNAL_API_KEY=EXTERNAL_API_KEY:latest \
      ...
    
    Your application can then access process.env.EXTERNAL_API_KEY.
  4. Direct Access (less common): Alternatively, your application can directly call the Secret Manager API using the Google Cloud client libraries, but environment variables are generally simpler for configuration.

Q4: What if my tool execution takes longer than the Cloud Run request timeout?

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:

  1. Asynchronous Task Queue: The MCP server initiates a long-running task (e.g., by publishing a message to Google Cloud Pub/Sub or creating a Cloud Tasks entry). It then immediately returns an MCPResponse indicating the task has been accepted, possibly with a task_id.
  2. Polling: The client can then periodically poll a separate endpoint on your MCP server (or another service) with the task_id to check for completion and retrieve results.
  3. Webhooks: The long-running task, once complete, can send a webhook notification to a dedicated endpoint on your MCP server (or another service) to push results back to the client if the client maintains a persistent connection or has a way to receive asynchronous updates. This decouples the request-response cycle from the actual execution time.

Q5: How can I test my stdio server locally?

A5: You can pipe JSON data to its stdin.

  1. Compile the server: npm run build

  2. Prepare a request file:

    json
    // request.json
    {
      "request_id": "test-stdio-1",
      "tool_calls": [
        { "call_id": "call-stdio-1", "name": "search", "input": { "query": "stdio transport" } }
      ]
    }
    
  3. Test your server interactively with the official MCP Inspector:

    bash
    # 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:

    bash
    # 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).
    
Advertisement
Share this article:

Stay Updated

Get the latest posts delivered straight to your inbox.

Free Developer Utilities

Free In-Browser Developer Tools

Clean AI CLI logs, build cron expressions, decode JWTs, and calculate chmod permissions offline.

Explore Tools

Related Articles

Building a Custom MCP Client: Connecting Any LLM to Multiple Model Context Protocol Servers
aiOctober 1, 2026

Building a Custom MCP Client: Connecting Any LLM to Multiple Model Context Protocol Servers

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
Remote MCP Servers in Production: Streamable HTTP, OAuth 2.1 & Enterprise Gateway Architecture
mcpNovember 10, 2026

Remote MCP Servers in Production: Streamable HTTP, OAuth 2.1 & Enterprise Gateway Architecture

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
Building Production MCP Servers on Cloudflare Workers, KV & Durable Objects
mcpOctober 27, 2026

Building Production MCP Servers on Cloudflare Workers, KV & Durable Objects

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
On this page
0%
  • Core MCP Server Architecture
  • Project Setup
  • Schema Definition and Tool Validation with Zod
  • Implementing Tools, Resources, and Prompts with @modelcontextprotocol/sdk
  • Transport Layer: Stdio vs. SSE
  • Main Server Entry Point
  • Transport Comparison
  • Containerization with Docker
  • Deployment to Google Cloud Run
  • Prerequisites
  • Deployment Steps
  • Production Gotchas & Troubleshooting
  • Test Your Knowledge
  • Frequently Asked Questions
  • Q1: How do I add a new custom tool or resource to my MCP server?
  • Q2: Can I use WebSockets instead of SSE for bidirectional streaming?
  • Q3: How do I manage secrets (e.g., API keys for external tools) in a Cloud Run MCP server?
  • Q4: What if my tool execution takes longer than the Cloud Run request timeout?
  • Q5: How can I test my stdio server locally?
PreviousBigQuery + Cloud Run: Building a Production Serverless Data Ingestion PipelineRead Nextpgvector vs Qdrant at Scale: Memory Overhead, HNSW Recall & Tail Latencies (2026)