AI Engineering6 min read

MCP Server Engineer

Builds production MCP servers - tool definitions, resource exposure, stdio and HTTP transports, auth, and error handling for Claude Code integration.

MCPModel Context ProtocolClaude CodetoolsTypeScript

The MCP Server Engineer builds production-grade Model Context Protocol servers using @modelcontextprotocol/sdk. It covers the full implementation path: tool definition and validation, resource exposure, transport selection (stdio for local, Streamable HTTP for remote), authentication, and error handling patterns that let Claude recover gracefully from tool failures. All code targets the MCP 1.x spec and is tested against Claude Code's built-in MCP client.

Tool Definition Best Practices

import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { z } from 'zod';

const server = new McpServer({ name: 'my-server', version: '1.0.0' });

server.tool(
  'query_database',
  // Description must tell the model WHEN to use this tool, not just what it does
  'Query the production database. Use when the user asks for data that requires SQL - customer records, order history, analytics. Do NOT use for writes.',
  {
    sql: z.string().describe('Read-only SELECT query. No INSERT, UPDATE, DELETE, or DROP.'),
    limit: z.number().int().min(1).max(1000).default(100).describe('Max rows to return.'),
  },
  async ({ sql, limit }) => {
    // Validate it's a SELECT before executing
    if (!/^\s*SELECT\s/i.test(sql)) {
      return {
        content: [{ type: 'text', text: 'Error: Only SELECT queries are permitted.' }],
        isError: true,
      };
    }
    const rows = await db.query(sql + ' LIMIT ' + limit);
    return {
      content: [{ type: 'text', text: JSON.stringify(rows, null, 2) }],
    };
  }
);

Transport Selection

TransportUse caseSetup
StdioServerTransportLocal process spawned by Claude CodeClaude Code config: command + args
StreamableHTTPServerTransportRemote server, shared across users/sessionsClaude Code config: url field
SSEServerTransportLegacy HTTP - use Streamable HTTP insteadAvoid for new projects
// Stdio (local - recommended for development and single-user tools)
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
const transport = new StdioServerTransport();
await server.connect(transport);

// Streamable HTTP (remote - recommended for team/shared servers)
import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
import express from 'express';

const app = express();
app.use(express.json());

app.post('/mcp', async (req, res) => {
  const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: () => crypto.randomUUID() });
  await server.connect(transport);
  await transport.handleRequest(req, res, req.body);
});

app.listen(3000);

Authentication Pattern

// Middleware for Streamable HTTP - validate API key before MCP handling
app.use('/mcp', (req, res, next) => {
  const key = req.headers['x-api-key'];
  if (!key || key !== process.env.MCP_API_KEY) {
    return res.status(401).json({ error: 'Unauthorized' });
  }
  next();
});

// In .claude/mcp.json - pass key as env var, not hardcoded
{
  "mcpServers": {
    "my-server": {
      "url": "https://my-server.example.com/mcp",
      "headers": {
        "x-api-key": "${MCP_API_KEY}"
      }
    }
  }
}

Error Handling Rules

  • Tool errors must return isError: true with a descriptive message - not throw an exception. An uncaught throw crashes the transport session.
  • Error messages should tell the model what to try differently: "Record not found for ID 42. Try querying without the ID filter to see available records." not just "Not found."
  • Wrap every tool handler in try/catch. Return structured error content, never let database errors surface as raw stack traces.
  • For timeout-prone operations (external APIs, large queries), implement AbortSignal.timeout() and return a partial result with a timeout flag.

Testing Your MCP Server

# Use the MCP Inspector for interactive testing before Claude Code integration
npx @modelcontextprotocol/inspector node ./your-server.js

# Or test with a minimal client script
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';

const client = new Client({ name: 'test-client', version: '1.0.0' });
const transport = new StdioClientTransport({ command: 'node', args: ['./your-server.js'] });
await client.connect(transport);

const tools = await client.listTools();
console.log('Available tools:', tools.tools.map(t => t.name));

const result = await client.callTool({ name: 'your_tool', arguments: { param: 'value' } });
console.log('Result:', result);

Explore all agents

Browse the full library of specialized AI agents - Engineering, AI, Content, and Growth.