How many times have you watched Claude Code hit a wall because it couldn’t access your internal APIs? Your team has built sophisticated services, authentication systems, and data pipelines—but they’re locked behind corporate firewalls and proprietary authentication schemes. Claude Code has incredible reasoning abilities, but without direct access to your internal tools, it’s working with one hand tied behind its back.
The solution? Build a custom MCP (Model Context Protocol) server that wraps your existing internal APIs. This isn’t about reinventing the wheel. It’s about creating a smart adapter layer that translates Claude Code’s requests into your internal API calls, handles all the gnarly authentication and rate limiting headaches, and gives Claude safe, structured access to the exact data and operations your team actually uses.
In this guide, we’ll walk through designing and implementing a custom MCP server that maps to real internal services. We’ll tackle the hard problems: schema design, request translation, authentication passthrough, error handling, and deployment. By the end, you’ll have a blueprint for wrapping any internal API in an MCP server.
Why MCP for Internal APIs?
Before we dive into implementation, let’s talk about why MCP is the right pattern here.
MCP creates a clean contract between clients (like Claude Code) and services. It defines tool schemas upfront, which Claude Code uses to understand what operations are available, what parameters they need, and what they return. No more fuzzy natural language negotiations about “what can you actually do?” The schema is the contract.
Contrast this with raw REST API access: Claude Code would need explicit instructions about every endpoint, parameter validation, authentication method, and error handling pattern. That scales terribly. The moment your API changes, you need to update documentation and retrain Claude Code on the new patterns.
With MCP, you define the interface once. Claude Code learns it immediately. Changes to your internal implementation (as long as the external schema stays the same) don’t affect Claude Code’s ability to use the service. You also get built-in tool use infrastructure: request/response serialization, error handling conventions, and the ability to reason about which tools to invoke.
There’s also a security angle. An MCP server sits between Claude Code and your internal APIs. It’s your chokepoint for authentication, rate limiting, audit logging, and permission checks. You don’t have to trust Claude Code with raw API credentials. Instead, you trust your MCP server to enforce policy.
Think of your MCP server as a security perimeter. Claude Code is untrusted by default. Your server validates every request, checks rate limits, authenticates with your internal systems, and returns only what should be visible. This is far better than hoping Claude Code won’t misuse credentials or accidentally leak sensitive data.
Designing Schemas That Map to Real APIs
The first step is schema design. Your MCP server needs to expose operations as tools, and each tool needs a JSON Schema describing its parameters and output.
Let’s say you have an internal service that manages customer data: fetch customer info, update profiles, run analytics queries. Your backend might be a REST API with endpoints like GET /api/v1/customers/:id and POST /api/v1/customers/:id/update. Your job is to expose these as MCP tools.
Here’s a simple example. Your REST API looks like:
GET /api/v1/customers/{customerId}
POST /api/v1/customers/{customerId}
DELETE /api/v1/customers/{customerId}
You’ll expose these as three MCP tools. The schema design principle is: each tool should map to a coherent operation, and parameters should be explicit and typed. Don’t just proxy the raw endpoint parameters. Think about what Claude Code actually needs to accomplish.
// Define tool schemas that wrap your internal API
const customerToolSchemas = {
getCustomer: {
name: "get_customer",
description:
"Fetch a customer record by ID. Returns name, email, account status, and metadata.",
inputSchema: {
type: "object",
properties: {
customerId: {
type: "string",
description: "The unique customer identifier (e.g., cust_abc123)",
},
includeHistory: {
type: "boolean",
description:
"If true, include transaction history and lifecycle events (optional, default false)",
default: false,
},
},
required: ["customerId"],
},
},
updateCustomer: {
name: "update_customer",
description:
"Update a customer's profile. Returns updated customer record.",
inputSchema: {
type: "object",
properties: {
customerId: {
type: "string",
description: "The customer ID to update",
},
email: {
type: "string",
description: "New email address (optional)",
},
metadata: {
type: "object",
description:
"Key-value pairs to update in customer metadata (optional)",
additionalProperties: true,
},
},
required: ["customerId"],
additionalProperties: false,
},
},
};
Notice the intentionality here. We’re not exposing raw query parameters. We’re exposing business-level operations with clear descriptions. The includeHistory parameter is optional and defaults to false—a smart default that avoids expensive queries unless Claude Code specifically needs them.
The descriptions matter. Claude Code reads these to decide whether a tool is relevant to the user’s request. “Fetch a customer record by ID” is more useful than “GET endpoint for customers resource.”
Good schema design means your MCP server stays stable even as your internal APIs evolve. If your backend adds a new optional field to the customer response, your schema doesn’t break. If you add optional parameters for future filtering, Claude Code handles them automatically.
Implementing Request Translation
Now the tricky part: translating MCP requests into your internal API calls.
Your MCP server receives a tool invocation with structured parameters. It needs to:
- Validate those parameters against the schema
- Transform them into API requests (possibly with authentication)
- Handle the API response
- Transform the response back into something Claude Code can use
Let’s build a handler for the getCustomer tool:
interface GetCustomerInput {
customerId: string;
includeHistory?: boolean;
}
interface CustomerRecord {
id: string;
email: string;
name: string;
status: "active" | "suspended" | "deleted";
createdAt: string;
history?: Array<{
timestamp: string;
event: string;
details: Record<string, unknown>;
}>;
}
class InternalAPIAdapter {
private baseURL: string;
private serviceToken: string;
constructor(baseURL: string, serviceToken: string) {
this.baseURL = baseURL;
this.serviceToken = serviceToken;
}
async handleGetCustomer(input: GetCustomerInput): Promise<CustomerRecord> {
try {
// Build the API request
// The MCP parameter is customerId; the API endpoint is /api/v1/customers/{id}
const response = await axios.get(
`${this.baseURL}/api/v1/customers/${encodeURIComponent(input.customerId)}`,
{
headers: {
Authorization: `Bearer ${this.serviceToken}`,
"Content-Type": "application/json",
},
params: input.includeHistory ? { include: "history" } : {},
},
);
// Validate the response shape
if (!response.data || !response.data.id) {
throw new Error(
"Invalid response from internal API: missing customer id",
);
}
// Transform and return
return response.data as CustomerRecord;
} catch (error) {
// Handle errors gracefully (we'll dive deeper into error mapping next)
if (axios.isAxiosError(error)) {
if (error.response?.status === 404) {
throw new Error(`Customer not found: ${input.customerId}`);
}
if (error.response?.status === 401) {
throw new Error(
"Authentication failed - service token may be invalid",
);
}
}
throw error;
}
}
}
// Usage example
const adapter = new InternalAPIAdapter(
"https://internal-api.company.com",
process.env.INTERNAL_SERVICE_TOKEN || "",
);
// When Claude Code invokes the tool with these parameters:
const result = await adapter.handleGetCustomer({
customerId: "cust_abc123",
includeHistory: true,
});
// The adapter:
// 1. Encodes the customerId safely
// 2. Adds authentication headers
// 3. Passes includeHistory as a query parameter
// 4. Handles 404/401 errors specifically
// 5. Returns the customer record
The key insight: parameters map to either URL path segments, query strings, or request bodies. The translation logic isn’t magical; it’s just careful URL construction and proper header management.
One important detail: see how we’re using encodeURIComponent? That’s critical. If a customer ID contains special characters, you need to percent-encode it. Claude Code doesn’t know (or care) about URL encoding. Your adapter handles it transparently. This is why a translation layer matters—it handles all these implementation details that Claude Code shouldn’t have to know about.
Handling Authentication Passthrough
Here’s where many teams stumble. You’ve got internal APIs that require authentication—tokens, service accounts, OAuth flows, custom headers. Your MCP server needs to bridge that gap.
You have three main patterns:
Pattern 1: Service Account (Recommended for most cases)
Your MCP server has a service account credential (environment variable, secrets manager, etc.) that allows it to call your internal APIs on behalf of all Claude Code users. This works when:
- The internal API supports service accounts
- You trust your MCP server deployment
- You can audit actions through the service account logs
- The internal API doesn’t need to know who the end user is
Service accounts are simple, secure, and audit-friendly. One credential manages access to your entire system.
Pattern 2: Token Passthrough
Claude Code users provide their own credentials, which the MCP server passes through. This works when:
- Users have individual API tokens
- Your internal API validates per-user permissions
- You want fine-grained audit trails (per user)
- Users are comfortable managing their own tokens
This pattern requires more infrastructure but gives you precise user-level tracking.
Pattern 3: Hybrid
The MCP server uses a service account to access internal APIs, but records which Claude Code user made each request. The internal API trusts the service account; you audit at the MCP layer.
Let’s implement the service account pattern with production-ready error handling and rate limiting:
interface MCPToolRequest {
name: string;
arguments: Record<string, unknown>;
}
class MCPServerWithAuth {
private apiClient: AxiosInstance;
private rateLimitTracker: Map<string, number[]> = new Map();
private readonly MAX_REQUESTS_PER_MINUTE = 60;
private readonly SERVICE_TOKEN: string;
constructor(internalAPIBase: string, serviceToken: string) {
this.SERVICE_TOKEN = serviceToken;
this.apiClient = axios.create({
baseURL: internalAPIBase,
headers: {
Authorization: `Bearer ${serviceToken}`,
"Content-Type": "application/json",
"User-Agent": "MCP-Server/1.0",
},
timeout: 10000, // 10 second timeout
});
}
private async checkRateLimit(toolName: string): Promise<void> {
const now = Date.now();
const oneMinuteAgo = now - 60000;
if (!this.rateLimitTracker.has(toolName)) {
this.rateLimitTracker.set(toolName, []);
}
const timestamps = this.rateLimitTracker.get(toolName)!;
const recentRequests = timestamps.filter((t) => t > oneMinuteAgo);
if (recentRequests.length >= this.MAX_REQUESTS_PER_MINUTE) {
throw new Error(
`Rate limit exceeded for ${toolName}: ` +
`${recentRequests.length}/${this.MAX_REQUESTS_PER_MINUTE} requests in last minute`,
);
}
recentRequests.push(now);
this.rateLimitTracker.set(toolName, recentRequests);
}
async invokeTool(request: MCPToolRequest): Promise<unknown> {
// Check rate limits before anything else
await this.checkRateLimit(request.name);
// Dispatch to the appropriate handler based on tool name
switch (request.name) {
case "get_customer":
return await this.handleGetCustomerWithRetry(
request.arguments as { customerId: string; includeHistory?: boolean },
);
case "update_customer":
return await this.handleUpdateCustomer(
request.arguments as {
customerId: string;
email?: string;
metadata?: Record<string, unknown>;
},
);
default:
throw new Error(`Unknown tool: ${request.name}`);
}
}
private async handleGetCustomerWithRetry(input: {
customerId: string;
includeHistory?: boolean;
}): Promise<unknown> {
// Use exponential backoff for transient failures
return await pRetry(
async () => {
const response = await this.apiClient.get(
`/api/v1/customers/${encodeURIComponent(input.customerId)}`,
{
params: input.includeHistory ? { include: "history" } : {},
},
);
return response.data;
},
{
retries: 3,
minTimeout: 1000,
maxTimeout: 10000,
onFailedAttempt: (error) => {
console.error(
`Attempt ${error.attemptNumber} failed: ${error.message}`,
);
},
},
);
}
private async handleUpdateCustomer(input: {
customerId: string;
email?: string;
metadata?: Record<string, unknown>;
}): Promise<unknown> {
const payload: Record<string, unknown> = {};
if (input.email) {
payload.email = input.email;
}
if (input.metadata) {
payload.metadata = input.metadata;
}
const response = await this.apiClient.post(
`/api/v1/customers/${encodeURIComponent(input.customerId)}`,
payload,
);
return response.data;
}
}
// Instantiate with credentials from environment
const server = new MCPServerWithAuth(
process.env.INTERNAL_API_BASE_URL || "https://api.internal.company.com",
process.env.INTERNAL_SERVICE_TOKEN || "",
);
// Example invocation (Claude Code would call this via MCP protocol)
try {
const result = await server.invokeTool({
name: "get_customer",
arguments: {
customerId: "cust_xyz789",
includeHistory: true,
},
});
console.log("Success:", result);
} catch (error) {
console.error("Tool invocation failed:", error);
}
Notice several production-ready details:
- Service token from environment: Never hardcode credentials. Use environment variables or a secrets manager.
- Rate limiting: We track requests per tool per minute. This prevents accidental DoS of your internal API.
- Exponential backoff: Transient failures (network hiccups, temporary service issues) are retried automatically with increasing wait times.
- Timeout configuration: We set a 10-second timeout. If the internal API is slow, we fail fast rather than hanging Claude Code.
- Error context: When things go wrong, the error messages are actionable (rate limit exceeded, authentication failed, etc.).
These details matter in production. Without rate limiting, a busy Claude Code session could hammer your internal API. Without timeouts, requests could hang indefinitely. Without exponential backoff, transient failures become permanent failures.
Error Mapping and Graceful Degradation
Your internal APIs will fail. Networks are unreliable. Services go down. Permissions are denied. Your MCP server needs to translate these failures into clear, actionable errors for Claude Code.
Here’s the principle: map internal API errors to semantic categories that Claude Code can reason about.
type ErrorCategory =
| "not_found"
| "permission_denied"
| "invalid_input"
| "rate_limited"
| "service_unavailable"
| "unknown";
interface MappedError {
category: ErrorCategory;
message: string;
retryable: boolean;
userFacingMessage: string;
}
function mapInternalAPIError(error: unknown): MappedError {
// Handle axios errors
if (axios.isAxiosError(error)) {
const status = error.response?.status;
const data = error.response?.data as Record<string, unknown> | undefined;
switch (status) {
case 404:
return {
category: "not_found",
message: `Resource not found: ${data?.error || error.message}`,
retryable: false,
userFacingMessage: "The requested resource does not exist.",
};
case 401:
case 403:
return {
category: "permission_denied",
message: `Access denied: ${data?.error || error.message}`,
retryable: false,
userFacingMessage:
"You do not have permission to access this resource.",
};
case 400:
return {
category: "invalid_input",
message: `Invalid request: ${data?.error || error.message}`,
retryable: false,
userFacingMessage: "The request was invalid. Check the parameters.",
};
case 429:
return {
category: "rate_limited",
message: `Rate limit exceeded: ${data?.error || error.message}`,
retryable: true,
userFacingMessage:
"Rate limit exceeded. Please try again in a moment.",
};
case 502:
case 503:
case 504:
return {
category: "service_unavailable",
message: `Service unavailable (${status}): ${error.message}`,
retryable: true,
userFacingMessage:
"The service is temporarily unavailable. Please try again.",
};
default:
return {
category: "unknown",
message: `HTTP ${status}: ${error.message}`,
retryable: false,
userFacingMessage: `An error occurred: ${error.message}`,
};
}
}
// Handle timeout errors
if (error instanceof Error && error.message.includes("timeout")) {
return {
category: "service_unavailable",
message: `Request timeout: ${error.message}`,
retryable: true,
userFacingMessage: "The request took too long. Please try again.",
};
}
// Fallback for unexpected errors
return {
category: "unknown",
message: error instanceof Error ? error.message : String(error),
retryable: false,
userFacingMessage: "An unexpected error occurred.",
};
}
// When Claude Code invokes a tool and it fails:
async function handleToolInvocationWithErrorMapping(
toolName: string,
args: Record<string, unknown>,
): Promise<{ success: boolean; data?: unknown; error?: MappedError }> {
try {
const result = await server.invokeTool({ name: toolName, arguments: args });
return { success: true, data: result };
} catch (error) {
const mappedError = mapInternalAPIError(error);
console.error(`Tool ${toolName} failed:`, mappedError);
return { success: false, error: mappedError };
}
}
Why does this matter? Claude Code sees the error category and message. It can decide whether to retry, whether to escalate to the user, or whether to try an alternative approach. A rate limit error is retryable; a permission error is not. A 404 means “this resource doesn’t exist”; a 503 means “service is overloaded, try again later.”
Good error mapping also prevents information leakage. Your internal API error might say “Database connection failed to replica-3.db.internal.” That’s implementation detail that shouldn’t escape to Claude Code. Your error mapper translates that to “Service temporarily unavailable” instead.
Deploying Your MCP Server
You’ve built the server locally. Now you need to deploy it so your team can actually use it.
There are a few deployment patterns:
Pattern 1: Localhost with Environment Variables (Development)
Perfect for testing. Claude Code connects to localhost:3000, and credentials come from .env.
Pattern 2: Docker Container + Kubernetes (Production)
Your MCP server runs as a microservice. It scales with your other services. Credentials come from secrets management (Kubernetes Secrets, AWS Secrets Manager, etc.).
Pattern 3: Serverless (AWS Lambda, Google Cloud Functions)
Stateless execution. Perfect for low-traffic scenarios. Cold starts might be slow, but you don’t pay for idle time.
Let’s build a simple Docker-based deployment:
# Dockerfile
FROM node:20-alpine
WORKDIR /app
# Copy package files and install dependencies
COPY package.json package-lock.json ./
RUN npm ci --only=production
# Copy source code
COPY src/ ./src/
# Expose MCP server port
EXPOSE 3000
# Health check
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
CMD node -e "require('http').get('https://automateanddeploy.com:3000/health', (r) => { if (r.statusCode !== 200) throw new Error(r.statusCode) })"
# Start the server
CMD ["node", "src/index.js"]
And a docker-compose for local development:
version: "3.9"
services:
mcp-server:
build: .
ports:
- "3000:3000"
environment:
INTERNAL_API_BASE_URL: https://api.internal.company.com
INTERNAL_SERVICE_TOKEN: ${INTERNAL_SERVICE_TOKEN}
LOG_LEVEL: debug
NODE_ENV: development
volumes:
- ./src:/app/src
healthcheck:
test: ["CMD", "curl", "-f", "https://automateanddeploy.com:3000/health"]
interval: 30s
timeout: 10s
retries: 3
Configuration should flow through environment variables, not hardcoded values. This lets you deploy the same Docker image to dev, staging, and production with different credentials.
// config.ts - load environment at startup
export const config = {
port: parseInt(process.env.PORT || "3000", 10),
internalAPIBase:
process.env.INTERNAL_API_BASE_URL || "https://api.internal.company.com",
serviceToken:
process.env.INTERNAL_SERVICE_TOKEN ||
(() => {
throw new Error(
"INTERNAL_SERVICE_TOKEN environment variable is required",
);
})(),
logLevel: process.env.LOG_LEVEL || "info",
nodeEnv: process.env.NODE_ENV || "development",
rateLimitPerMinute: parseInt(process.env.RATE_LIMIT_PER_MINUTE || "60", 10),
};
// Validate at startup, not at request time
if (!config.serviceToken) {
console.error(
"FATAL: Required environment variable INTERNAL_SERVICE_TOKEN is not set",
);
process.exit(1);
}
Common Pitfalls and How to Avoid Them
You’re about to implement this. Here are the gotchas we’ve hit and learned from:
Pitfall 1: Forgetting to Handle Slow APIs
Your internal service might be slow. If you set the timeout too high, Claude Code waits forever. If too low, you get spurious failures. Use circuit breakers: if the API is consistently slow, fail fast rather than letting requests pile up.
Pitfall 2: Leaking Internal Error Details
Your internal API error might say “Database connection failed to replica-3.db.internal.” That’s implementation detail. Don’t leak it to Claude Code. Map to “Service temporarily unavailable” instead. This prevents accidental security disclosure and makes errors more actionable.
Pitfall 3: Not Logging Request/Response Pairs
When things go wrong, you’ll want to know what Claude Code asked for and what your API returned. Log both. Make the logs searchable by request ID (use correlation IDs that flow from Claude Code through your MCP server through your internal API). This is invaluable for debugging.
Pitfall 4: Assuming API Responses Never Change
Your internal API evolves. Someone adds a new field. Your MCP server hardcodes assumptions about the response shape. Then it crashes. Use defensive parsing: validate response structure and fail gracefully if unexpected shapes arrive.
// Instead of assuming response.data.customer always exists:
const customer = response.data?.customer;
if (!customer) {
throw new Error(
"Unexpected API response: missing customer field. " +
`Response structure: ${JSON.stringify(Object.keys(response.data || {}))}`,
);
}
Pitfall 5: Not Testing the Authentication Path
You test with your credentials. The server works. You deploy it to production. Different credentials fail silently. Always test the actual credentials that will be used in production. Use a staging environment that mirrors production exactly.
Monitoring and Observability
Your MCP server will silently fail in production if you don’t have observability. You need to know when tools are timing out, when rate limits are hit, when authentication fails, and when Claude Code is making suspicious requests.
Set up structured logging from day one. Every tool invocation should log: the tool name, the arguments (sanitized to avoid logging sensitive data), the response time, any errors, and the outcome.
interface LogEntry {
timestamp: string;
toolName: string;
argumentsHash: string; // Hash, not actual args
responseTimeMs: number;
status: "success" | "error" | "timeout" | "rate_limited";
errorCategory?: ErrorCategory;
userId?: string; // If you're tracking per-user
}
class ObservableAdapter {
private logs: LogEntry[] = [];
async invokeWithObservability(
toolName: string,
args: Record<string, unknown>,
): Promise<unknown> {
const startTime = Date.now();
const argHash = this.hashArguments(args);
try {
const result = await this.invokeTool(toolName, args);
const responseTime = Date.now() - startTime;
this.logs.push({
timestamp: new Date().toISOString(),
toolName,
argumentsHash: argHash,
responseTimeMs: responseTime,
status: "success",
});
// Alert if slow
if (responseTime > 5000) {
console.warn(`Slow request: ${toolName} took ${responseTime}ms`);
}
return result;
} catch (error) {
const responseTime = Date.now() - startTime;
const mapped = mapInternalAPIError(error);
this.logs.push({
timestamp: new Date().toISOString(),
toolName,
argumentsHash: argHash,
responseTimeMs: responseTime,
status: mapped.retryable ? "error" : "error",
errorCategory: mapped.category,
});
throw error;
}
}
private hashArguments(args: Record<string, unknown>): string {
// Don't log actual args; just a hash so you can correlate requests
return Buffer.from(JSON.stringify(args))
.toString("base64")
.substring(0, 16);
}
}
Beyond logging, export metrics: success rate per tool, p50/p95/p99 latency, error categories, and rate limit hits. If you’re using Prometheus or Datadog, emit metrics that your monitoring system can scrape.
// Emit Prometheus metrics
const toolInvocations = new client.Counter({
name: "mcp_tool_invocations_total",
help: "Total tool invocations",
labelNames: ["tool_name", "status"],
});
const toolLatency = new client.Histogram({
name: "mcp_tool_latency_ms",
help: "Tool invocation latency in milliseconds",
labelNames: ["tool_name"],
buckets: [10, 50, 100, 500, 1000, 5000],
});
// In your invocation handler:
const endTimer = toolLatency.startTimer({ tool_name: toolName });
try {
const result = await this.invokeTool(toolName, args);
toolInvocations.inc({ tool_name: toolName, status: "success" });
endTimer();
return result;
} catch (error) {
toolInvocations.inc({ tool_name: toolName, status: "error" });
endTimer();
throw error;
}
With these metrics, you’ll notice when something is wrong before Claude Code users do. You’ll see latency increase, error rates spike, or specific tools consistently fail.
Scaling Considerations
Your MCP server might start handling one internal service. Then you add another. Then another. Before long, you’re proxying requests to five different internal APIs, each with different auth methods, rate limits, and error patterns.
Plan for this scaling. Use the adapter pattern: wrap each internal service in its own class with its own error handling, rate limiting, and retry logic. Compose these adapters in your main server.
class CompositeAdapter {
private customerAdapter: InternalAPIAdapter;
private analyticsAdapter: InternalAPIAdapter;
private billingAdapter: InternalAPIAdapter;
constructor() {
this.customerAdapter = new InternalAPIAdapter(
process.env.CUSTOMER_API_URL!,
process.env.CUSTOMER_API_TOKEN!,
);
this.analyticsAdapter = new InternalAPIAdapter(
process.env.ANALYTICS_API_URL!,
process.env.ANALYTICS_API_TOKEN!,
);
this.billingAdapter = new InternalAPIAdapter(
process.env.BILLING_API_URL!,
process.env.BILLING_API_TOKEN!,
);
}
async invokeTool(
toolName: string,
args: Record<string, unknown>,
): Promise<unknown> {
if (toolName.startsWith("customer_")) {
return await this.customerAdapter.invokeTool(toolName, args);
}
if (toolName.startsWith("analytics_")) {
return await this.analyticsAdapter.invokeTool(toolName, args);
}
if (toolName.startsWith("billing_")) {
return await this.billingAdapter.invokeTool(toolName, args);
}
throw new Error(`Unknown tool: ${toolName}`);
}
}
Each adapter is independent. If the analytics API goes down, customer and billing tools still work. If the analytics API has a different rate limit (say, 100 requests/minute vs. your default 60), you can configure it separately. This composability is why the adapter pattern scales.
Real-World Example: Shipping an MCP Server
Let’s walk through a realistic scenario. You have a customer database API (REST), a search service (Elasticsearch), and a CRM system (proprietary SDK). You want Claude Code to be able to search customers, get detailed customer info, and log notes to the CRM.
You’d create three tool schemas:
const toolSchemas = {
search_customers: {
name: "search_customers",
description: "Search for customers by name or email using Elasticsearch",
inputSchema: {
type: "object",
properties: {
query: {
type: "string",
description: "Search query (name or email partial match)",
},
limit: {
type: "number",
description: "Max results to return (default 10)",
default: 10,
},
},
required: ["query"],
},
},
get_customer_details: {
name: "get_customer_details",
description: "Get full customer profile including purchase history",
inputSchema: {
type: "object",
properties: {
customerId: {
type: "string",
description: "Customer ID from search results",
},
},
required: ["customerId"],
},
},
add_crm_note: {
name: "add_crm_note",
description: "Add a note to a customer record in the CRM",
inputSchema: {
type: "object",
properties: {
customerId: {
type: "string",
description: "Customer ID",
},
note: {
type: "string",
description: "The note to add",
},
},
required: ["customerId", "note"],
},
},
};
Your adapter would handle the translation:
async searchCustomers(query: string, limit: number = 10): Promise<SearchResult[]> {
// Translate to Elasticsearch query
const esQuery = {
query: {
multi_match: {
query,
fields: ['name', 'email']
}
},
size: limit
};
const response = await this.elasticsearchClient.search({
index: 'customers',
body: esQuery
});
return response.body.hits.hits.map(hit => ({
id: hit._source.id,
name: hit._source.name,
email: hit._source.email
}));
}
async getCustomerDetails(customerId: string): Promise<CustomerDetail> {
// Fetch from REST API
const response = await this.httpClient.get(`/api/v1/customers/${customerId}`);
return response.data;
}
async addCRMNote(customerId: string, note: string): Promise<void> {
// Use CRM SDK
const customer = await this.crmClient.getCustomer(customerId);
if (!customer) {
throw new Error(`Customer not found in CRM: ${customerId}`);
}
await this.crmClient.addNote(customer.id, {
text: note,
timestamp: new Date(),
source: 'MCP-Server'
});
}
Deploy this, and suddenly Claude Code can search your customer database, pull detailed info, and log interactions back to your CRM. All through a single MCP server. All with rate limiting, error handling, and audit trails built in.
Putting It All Together
Here’s a minimal but complete MCP server example, structured for production:
// src/index.ts - Entry point
const app = express();
const mcpServer = new MCPServerWithAuth(
config.internalAPIBase,
config.serviceToken,
);
// Health check endpoint
app.get("/health", (req, res) => {
res.json({ status: "ok", timestamp: new Date().toISOString() });
});
// MCP tool invocation endpoint
app.post("/tool/invoke", express.json(), async (req, res) => {
try {
const { name, arguments: args } = req.body;
if (!name || typeof name !== "string") {
return res.status(400).json({ error: "Missing or invalid tool name" });
}
logger.info(`Invoking tool: ${name}`, { arguments: args });
const result = await mcpServer.invokeTool({ name, arguments: args });
res.json({ success: true, data: result });
} catch (error) {
logger.error(`Tool invocation failed: ${(error as Error).message}`);
res.status(500).json({
success: false,
error: (error as Error).message,
});
}
});
// List available tools
app.get("/tools", (req, res) => {
res.json({
tools: [config.toolSchemas.getCustomer, config.toolSchemas.updateCustomer],
});
});
app.listen(config.port, () => {
logger.info(`MCP Server listening on port ${config.port}`);
});
This assumes you have src/config.ts, src/mcp-server.ts, src/handlers.ts, and src/logger.ts already defined as we discussed above.
Testing and Validation
Before deploying your MCP server to production, you need to verify it works correctly under real conditions. Testing an MCP server is different from testing a typical API because you’re testing the translation layer, not just the endpoints.
Start with unit tests for your adapter classes. Test successful requests and failures separately. Mock the internal API responses so you can verify your error mapping works. Test edge cases: what happens when a required parameter is missing? What happens when the internal API returns an unexpected shape?
describe("InternalAPIAdapter", () => {
it("should handle 404 errors gracefully", async () => {
// Mock axios to return 404
const adapter = new InternalAPIAdapter("https://api.example.com", "token");
// Assert that NotFoundError is thrown
// Assert that error message is user-friendly
});
it("should retry on transient failures", async () => {
// Mock axios to fail twice, then succeed
// Assert that request was retried
// Assert that exponential backoff was respected
});
it("should respect rate limits", async () => {
// Invoke tool 65 times rapidly
// Assert that 61st+ invocations fail with rate limit error
});
});
Integration testing is where the real validation happens. Test against a staging version of your internal API. Use the actual credentials that will be used in production. Test entire workflows: search for a customer, fetch their details, update their profile. Make sure everything works end-to-end.
Create a test suite that exercises all tools. Document expected inputs and outputs. This becomes your validation checklist before any production deployment.
Operational Runbooks and Troubleshooting
Once your MCP server is running, document how to troubleshoot when things go wrong. Create runbooks for common failure scenarios:
Symptom: “Tool invocation timeout”
Likely cause: Internal API is slow
Solution: Check internal API health; increase timeout if intentional slowness; consider caching responses
Symptom: “Rate limit exceeded for tool X”
Likely cause: Claude Code is invoking tool too frequently
Solution: Increase rate limit if legitimate usage; add backpressure (tell Claude Code to wait)
Symptom: “Authentication failed”
Likely cause: Service token expired or invalid
Solution: Rotate service token; verify it’s set in environment; check internal API access logs
Symptom: “Tool returns unexpected schema”
Likely cause: Internal API changed; response includes new fields
Solution: Update adapter to handle new fields; add defensive parsing; verify API version
Keep these runbooks next to your monitoring dashboard. When alerts fire, ops teams can follow the runbook to resolve quickly.
Cost Considerations and Optimization
Running an MCP server costs money. If you deploy it to Kubernetes, you pay for compute. If you use serverless, you pay per invocation. Understanding and optimizing these costs matters critically.
Measure actual traffic. How often does Claude Code invoke each tool? Are there patterns? Do certain times of day see more traffic? This data informs sizing decisions. Start by instrumenting every tool invocation with cost tracking. Log the resource consumption of each internal API call. Over time, you’ll identify which tools are expensive and which are cheap.
Consider caching responses from expensive internal APIs. If Claude Code frequently asks for the same customer data, cache the response for a few seconds. This reduces load on your internal system and responds faster to Claude Code. Caching is particularly valuable for read-heavy operations like searching and fetching data. For write operations, be cautious—stale data could cause problems.
Implement request deduplication. If Claude Code makes the same request twice within seconds (which happens when Claude Code retries), return the cached result from the first request. This prevents thundering herd problems and dramatically reduces load on expensive operations. You can use a simple in-memory cache with a TTL (time-to-live) to keep things manageable.
Monitor your costs continuously. Track API calls per tool. Identify expensive operations. Create dashboards showing cost per tool per day. If a particular tool is expensive, consider rate limiting it more aggressively or adding a warning to Claude Code. Some operations should carry a cost signal—if it’s expensive, you want Claude Code to know.
Batch operations where possible. If Claude Code needs data about ten customers, can you fetch all ten in one batch request rather than ten individual requests? Design your MCP tools to support batching. This reduces API calls significantly.
Advanced Authorization Patterns
As your MCP server grows, you might need finer-grained authorization. Maybe some Claude Code users should only access certain tools. Maybe some tools should only work on certain resources.
Implement authorization at the MCP server layer:
interface AuthContext {
userId: string;
roles: string[];
permissions: string[];
}
async function authorizeToolInvocation(
context: AuthContext,
toolName: string,
args: Record<string, unknown>,
): Promise<boolean> {
// Check if user has permission for this tool
if (toolName === "delete_customer" && !context.roles.includes("admin")) {
return false;
}
// Check resource-level permissions
if (toolName === "get_customer_details") {
const customerId = args.customerId as string;
// Does this user have access to this customer?
const hasAccess = await checkCustomerAccess(context.userId, customerId);
return hasAccess;
}
return true;
}
This lets you implement multi-tenant scenarios, RBAC (role-based access control), and resource-level permissions. Claude Code stays the same; your MCP server enforces policy.
Handling Eventual Consistency
Some of your internal systems might be eventually consistent. If your search index is slightly behind your database, or if your cache is stale, Claude Code might get inconsistent results.
Be explicit about this in your tool descriptions. Tell Claude Code which results might be stale. If consistency matters, document the maximum staleness you guarantee.
You can also implement consistency checks in your MCP server:
async function getCustomerWithConsistencyCheck(
customerId: string,
requiredConsistency: "eventual" | "strong" = "eventual",
): Promise<CustomerRecord> {
const cachedResult = await cache.get(customerId);
if (requiredConsistency === "eventual" && cachedResult) {
return cachedResult;
}
// For strong consistency, always fetch fresh
const freshResult = await api.getCustomer(customerId);
await cache.set(customerId, freshResult, { ttl: 60 });
return freshResult;
}
This lets Claude Code choose consistency levels based on its needs. Sometimes “eventually consistent but fast” is fine. Sometimes you need the absolute current state.
Versioning Your MCP Server
As your MCP server evolves, you’ll add tools, change schemas, and modify behavior. You need a versioning strategy so you don’t break existing Claude Code integrations.
Semantic versioning is a good start: major.minor.patch. Major changes when you remove tools or change tool signatures. Minor changes when you add tools or optional parameters. Patch changes for bug fixes.
Document your versioning policy. Tell Claude Code integrations which version they’re using. Allow them to pin to specific versions if needed.
You can also version individual tools. Mark old tools as deprecated before removing them:
const customerToolSchemas = {
getCustomer: {
name: "get_customer",
description: "Fetch a customer record (stable, no plans to change)",
version: "1.0",
// ... rest of schema
},
getCustomerV1Deprecated: {
name: "get_customer_v1_deprecated",
description:
"DEPRECATED: Use get_customer instead. This will be removed in v2.0.0",
version: "1.0",
deprecated: true,
deprecatedAt: "2026-03-16",
removedAt: "2026-06-16",
// ... rest of schema
},
};
This gives Claude Code integrations time to migrate before tools disappear.
Integration with Your Internal Tools
Your MCP server can integrate with more than just your REST APIs. It can wrap:
- Message queues (RabbitMQ, Kafka): Create tools that publish messages
- Search engines (Elasticsearch, Algolia): Create tools that search data
- Databases (PostgreSQL, MongoDB): Create tools that query data directly
- File systems (S3, GCS): Create tools that read/write files
- Proprietary SDKs (Salesforce, Slack): Create tools that use vendor-specific libraries
The pattern is always the same: translate MCP tool invocations into calls to your internal systems, map responses and errors appropriately, and return results to Claude Code.
The key is consistency. Every tool should follow the same error handling pattern. Every tool should respect rate limits. Every tool should be logged and monitored. This consistency makes your MCP server a reliable, trustworthy integration point.
Security Best Practices
Your MCP server sits between Claude Code and your internal systems. This makes it a sensitive component. Treat security seriously.
Never log sensitive data. Your logs might be stored and accessed by multiple people. Don’t log API tokens, customer data, or query parameters that might contain secrets.
Use service accounts, not user credentials. If a service account is compromised, you can rotate it. If a user’s password is compromised, you’ve got bigger problems.
Validate all inputs. Claude Code shouldn’t send data you didn’t expect. Validate parameter types, ranges, and formats before passing them to internal APIs.
Use HTTPS for all communication. Between Claude Code and your MCP server, between your MCP server and internal APIs—always encrypt in transit.
Audit all access. Log which tools are invoked, when, and with what parameters (sanitized). This audit trail helps with compliance and forensics.
Rotate credentials regularly. Service tokens shouldn’t live forever. Establish a rotation schedule. When a developer leaves, rotate tokens they had access to.
Summary
Building a custom MCP server for internal APIs is a high-leverage investment. You create a single integration point, define it once with clear schemas, handle all the gnarly authentication and rate limiting details behind the scenes, and suddenly Claude Code has safe, structured access to your internal services.
The key principles:
- Schema first: Define tool contracts explicitly
- Translate, don’t proxy: Transform MCP requests into API calls, not the other way around
- Authenticate once: Service account pattern beats token passthrough for most cases
- Map errors semantically: Claude Code needs to understand categories, not raw API responses
- Deploy with config: Environment variables, not hardcoded values
- Test the real path: Use production credentials in a staging environment
- Monitor obsessively: Logs, metrics, and alerts from day one
- Secure relentlessly: Validate inputs, audit outputs, rotate credentials
- Document everything: Runbooks, schemas, and integration patterns
Your team will be amazed when Claude Code can suddenly reason about your internal data, run queries against your systems, and help with tasks that previously required manual API calls. And you did it safely, with rate limiting, error handling, and security built in from day one.
When you’re ready to scale, the adapter pattern lets you add new internal APIs without rewriting your MCP server. When you need to change authentication, you update one place. When an API changes, you update the translation layer without affecting Claude Code’s understanding.
This is the power of a well-designed adapter layer: it’s invisible to Claude Code, but it handles all the complexity that makes integration possible. Your team gains a powerful new capability, and you maintain control, visibility, and security throughout.
-iNet