Build an MCP Server for an Internal API
To let Claude Desktop or Cursor use a private REST API, put a small stdio MCP server in front of it: a few task-shaped tools, one HTTP helper that adds the base URL, token and timeout, and errors returned as tool results the model can read. Internal APIs rarely have an OpenAPI spec, and you do not need one.
This guide wraps an example helpdesk API in TypeScript and Python, starting from the scaffold MCP Server Generator downloads.
Both versions were run on 2026-10-18 (@modelcontextprotocol/sdk 1.32.1 on Node 20, mcp 2.3.0 with httpx 0.28.1 on Python 3.13) against a mock API, through an MCP client over stdio.
1. Pick tools, not endpoints
The model reads every tool name, description and schema on every turn, so a tool list should look like the jobs people ask for, not like your route table. Our example is an internal helpdesk with three routes:
| Internal route | MCP tool | Parameters |
|---|---|---|
GET /tickets?q=&status= | search_tickets | query (string, required), status (string, optional) |
GET /tickets/{id} | get_ticket | ticket_id (string, required) |
POST /tickets/{id}/comments | add_ticket_comment | ticket_id, body (strings, required) |
Rules that hold up on real internal APIs:
- Start read-only. Ship search and get tools first; add one write tool once you trust the setup. Leave delete and bulk operations out.
- Hide plumbing. Auth headers, tenant IDs, pagination cursors and API versions belong in the server, never in tool parameters.
- Write descriptions for the model. “Ticket ID, e.g. T-1042” tells it the format; “id” makes it guess.
- Keep it to roughly 3–15 tools. If you need dozens and already have a spec, read form generator vs OpenAPI→MCP tools.
2. Generate the scaffold
Open the generator form, name the server helpdesk-api, and enter the three tools from the table (untick required on status). Pick TypeScript or Python and download the ZIP (the Python MCP server generator is the same form, opened on Python). You get a project where every tool is registered with its schema and the handler is a placeholder:
src/index.ts as generated (one tool shown)
server.registerTool(
"search_tickets",
{
description: "Search internal support tickets by keyword and optional status",
inputSchema: z.object({
query: z.string().describe("Keywords to match in the ticket title"),
status: z.string().describe("open, pending or closed").optional()
}),
},
async ({ query, status }) => {
// TODO: replace this placeholder with real logic for search_tickets
const text = "[search_tickets] " + "query=" + JSON.stringify(query) + ", " + "status=" + JSON.stringify(status);
return {
content: [{ type: "text", text }],
};
}
);
Everything else in the scaffold (McpServer, StdioServerTransport, package.json, the README host config) stays as it is. The template guide explains each generated file. The next step replaces the TODOs with real HTTP calls.
3a. TypeScript: call the internal API
Add an api() helper below the McpServer constructor and point each handler at it. Node 18+ has fetch built in, so there are no new dependencies. This is the complete, tested file:
src/index.ts
#!/usr/bin/env node
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { z } from "zod";
const server = new McpServer({
name: "helpdesk-api",
version: "1.0.0",
});
// --- internal API client: one place for base URL, auth, timeout, errors ---
const API_URL = process.env.HELPDESK_API_URL;
const API_TOKEN = process.env.HELPDESK_API_TOKEN;
if (!API_URL || !API_TOKEN) {
console.error("Set HELPDESK_API_URL and HELPDESK_API_TOKEN");
process.exit(1);
}
async function api(method: string, path: string, body?: unknown): Promise<unknown> {
const res = await fetch(API_URL + path, {
method,
headers: {
Authorization: `Bearer ${API_TOKEN}`,
"Content-Type": "application/json",
},
body: body === undefined ? undefined : JSON.stringify(body),
signal: AbortSignal.timeout(10_000),
});
if (!res.ok) {
throw new Error(`${method} ${path} failed: HTTP ${res.status}`);
}
return res.json();
}
// Wrap a call so failures come back as a tool error the model can read.
async function asTool(call: () => Promise<unknown>) {
try {
const data = await call();
const text = JSON.stringify(data, null, 2).slice(0, 20_000);
return { content: [{ type: "text" as const, text }] };
} catch (err) {
// fetch hides the network reason in err.cause (ECONNREFUSED, ENOTFOUND...)
const code = (err as { cause?: { code?: string } }).cause?.code;
return {
content: [{ type: "text" as const, text: String(err) + (code ? ` (${code})` : "") }],
isError: true,
};
}
}
server.registerTool(
"search_tickets",
{
description: "Search internal support tickets by keyword and optional status",
inputSchema: z.object({
query: z.string().describe("Keywords to match in the ticket title"),
status: z.string().describe("open, pending or closed").optional(),
}),
},
async ({ query, status }) => {
const params = new URLSearchParams({ q: query });
if (status) params.set("status", status);
return asTool(() => api("GET", `/tickets?${params}`));
}
);
server.registerTool(
"get_ticket",
{
description: "Get one ticket with status, assignee and latest comments",
inputSchema: z.object({
ticket_id: z.string().describe("Ticket ID, e.g. T-1042"),
}),
},
async ({ ticket_id }) =>
asTool(() => api("GET", `/tickets/${encodeURIComponent(ticket_id)}`))
);
server.registerTool(
"add_ticket_comment",
{
description: "Add an internal comment to a ticket",
inputSchema: z.object({
ticket_id: z.string().describe("Ticket ID, e.g. T-1042"),
body: z.string().describe("Comment text"),
}),
},
async ({ ticket_id, body }) =>
asTool(() =>
api("POST", `/tickets/${encodeURIComponent(ticket_id)}/comments`, { body })
)
);
async function main() {
const transport = new StdioServerTransport();
await server.connect(transport);
console.error("helpdesk-api MCP server running on stdio");
}
main().catch((err) => {
console.error(err);
process.exit(1);
});
- Config comes from the environment. The server exits at startup with a message on stderr if
HELPDESK_API_URLorHELPDESK_API_TOKENis missing, which shows up in the host's MCP log. asTool()turns failures intoisError: trueresults likeError: GET /tickets/T-9999 failed: HTTP 404, so the model can tell the user, or retry with a different ID, instead of the call failing silently.encodeURIComponentkeeps a model-supplied ID from changing the path, and the output is capped at 20,000 characters so one big record cannot flood the context.
3b. Python: call the internal API
Add httpx to requirements.txt (and to dependencies in pyproject.toml if you launch with uv):
requirements.txt
mcp>=2.0.0
httpx>=0.27
Then switch the generated functions to async def and route them through one helper:
server.py
"""MCP server for the internal helpdesk API"""
import json
import os
from urllib.parse import quote
import httpx
from mcp.server import MCPServer
from mcp.server.mcpserver.exceptions import ToolError
mcp = MCPServer("helpdesk-api", version="1.0.0")
# --- internal API client: one place for base URL, auth, timeout, errors ---
API_URL = os.environ["HELPDESK_API_URL"]
API_TOKEN = os.environ["HELPDESK_API_TOKEN"]
async def api(method: str, path: str, **kwargs) -> str:
try:
async with httpx.AsyncClient(
base_url=API_URL,
headers={"Authorization": f"Bearer {API_TOKEN}"},
timeout=10.0,
) as client:
r = await client.request(method, path, **kwargs)
except httpx.TimeoutException as exc:
# str(exc) is empty for timeouts, so name the failure yourself.
raise ToolError(f"{method} {path} timed out after 10s") from exc
except httpx.HTTPError as exc:
raise ToolError(f"{method} {path} failed: {exc}") from exc
if r.is_error:
# ToolError -> isError: true with this message; other exceptions are hidden.
raise ToolError(f"{method} {path} failed: HTTP {r.status_code}")
try:
data = r.json()
except ValueError as exc:
# e.g. an SSO login page or proxy error page instead of JSON
ctype = r.headers.get("content-type", "no content-type")
raise ToolError(f"{method} {path} returned non-JSON ({ctype})") from exc
return json.dumps(data, indent=2)[:20_000]
@mcp.tool()
async def search_tickets(query: str, status: str = "") -> str:
"""Search internal support tickets by keyword and optional status
Args:
query: Keywords to match in the ticket title
status: open, pending or closed
"""
params = {"q": query}
if status:
params["status"] = status
return await api("GET", "/tickets", params=params)
@mcp.tool()
async def get_ticket(ticket_id: str) -> str:
"""Get one ticket with status, assignee and latest comments
Args:
ticket_id: Ticket ID, e.g. T-1042
"""
return await api("GET", f"/tickets/{quote(ticket_id, safe='')}")
@mcp.tool()
async def add_ticket_comment(ticket_id: str, body: str) -> str:
"""Add an internal comment to a ticket
Args:
ticket_id: Ticket ID, e.g. T-1042
body: Comment text
"""
return await api("POST", f"/tickets/{quote(ticket_id, safe='')}/comments", json={"body": body})
if __name__ == "__main__":
mcp.run()
- Raise
ToolError, not a plain exception. Inmcp2.x aToolErrormessage reaches the model (Error executing tool get_ticket: GET /tickets/T-9999 failed: HTTP 404). Any other exception is treated as a crash, and the model only seesError executing tool get_ticket. - Network failures are caught too (
httpx.HTTPError), so a VPN that is down reads as “All connection attempts failed” rather than a generic error. - Timeouts and non-JSON replies get their own message. An
httpxtimeout has an empty message, andr.json()on an HTML login page raises a plain exception that the model never sees. Both are turned intoToolErrors above; the table in step 5 shows the difference. - On
mcp1.x, importFastMCPfrommcp.server.fastmcpinstead ofMCPServer; the decorators are the same.
4. Pass the URL and token through the host config
Claude Desktop and Cursor both accept an env object per server. Start from the absolute-path config in the generated README and add it:
claude_desktop_config.json or .cursor/mcp.json
{
"mcpServers": {
"helpdesk-api": {
"command": "/absolute/path/to/helpdesk-api/node_modules/.bin/tsx",
"args": ["/absolute/path/to/helpdesk-api/src/index.ts"],
"env": {
"HELPDESK_API_URL": "https://helpdesk.internal.example.com/api",
"HELPDESK_API_TOKEN": "paste-a-scoped-token-here"
}
}
}
}
For Python, use .venv/bin/python and server.py as command and args, with the same env block. The server runs on your machine, so it reaches the API over whatever network you are on: if the API sits behind a VPN, the VPN has to be up. Config file locations and fixes for servers that do not appear are in connect an MCP server to Claude Desktop and Cursor.
5. Test before you connect a host
# TypeScript
HELPDESK_API_URL=https://helpdesk.internal.example.com/api \
HELPDESK_API_TOKEN=... \
npx @modelcontextprotocol/inspector npm start
# Python
HELPDESK_API_URL=https://helpdesk.internal.example.com/api \
HELPDESK_API_TOKEN=... \
npx @modelcontextprotocol/inspector .venv/bin/python server.py
In the Inspector, call each tool with a good input, an ID that does not exist, and a wrong token. In our run, both servers returned the matching ticket for search_tickets with {"query": "vpn", "status": "open"}, an isError result with the HTTP status for a 404 and a 401, and a readable error when the API was unreachable. If a tool only works on the happy path, the model will hit the other paths first. To script these checks with the Inspector CLI, see how to test an MCP server.
What the model sees when the internal API fails
We pointed both files above at a local mock of the helpdesk API and called get_ticket once per failure (2026-10-27, mcp 2.3.0 on Python 3.13.5, @modelcontextprotocol/sdk 1.32.2 on Node 20.19.2). This is the text each server returned to the host; every row except the first came back with isError: true.
| API behaviour | TypeScript (asTool) | Python (ToolError) |
|---|---|---|
| 200 with JSON | The ticket JSON | The ticket JSON |
| 404 unknown ID | Error: GET /tickets/T-404 failed: HTTP 404 | Error executing tool get_ticket: GET /tickets/T-404 failed: HTTP 404 |
| 401 wrong token | … failed: HTTP 401 | … failed: HTTP 401 |
| 500 server error | … failed: HTTP 500 | … failed: HTTP 500 |
| 200 with an HTML login page | SyntaxError: Unexpected token '<', "<html>login</html>" is not valid JSON | … returned non-JSON (text/html) |
| No answer within 10 s | TimeoutError: The operation was aborted due to timeout | … timed out after 10s |
| API host down (VPN off) | TypeError: fetch failed (ECONNREFUSED) | … failed: All connection attempts failed |
Token variable missing in env | Server exits 1 at startup: Set HELPDESK_API_URL and HELPDESK_API_TOKEN | Server exits 1 at startup: KeyError: 'HELPDESK_API_TOKEN' |
Two rows needed fixes that are already in the code above. Before them, the Python server answered the HTML page with only Error executing tool get_ticket and the timeout with … failed: and nothing after it, and the TypeScript server said just TypeError: fetch failed when the host was down. An HTML 200 usually means an SSO proxy or VPN portal answered instead of the API, so a message that says so saves a round of guessing. A server that exits at startup never reaches tools/list; the host shows it as failed or missing, and the reason is in the host's MCP log (see connect an MCP server for log locations).
6. Optional: share one server with your team over HTTP
With stdio, every person runs a copy of the server with their own API token. If you would rather run one server next to the internal API and let colleagues connect to a URL, switch to the Streamable HTTP transport and require a shared bearer token. The internal API token then stays in the server's environment and never reaches anyone's laptop.
TypeScript
src/team-http.ts
import { timingSafeEqual } from "node:crypto";
import type { NextFunction, Request, Response } from "express";
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
import { createMcpExpressApp } from "@modelcontextprotocol/sdk/server/express.js";
import { z } from "zod";
const SHARED_TOKEN = process.env.MCP_SHARED_TOKEN;
if (!SHARED_TOKEN) {
console.error("Set MCP_SHARED_TOKEN");
process.exit(1);
}
const PORT = Number(process.env.PORT ?? 3000);
// Hostnames clients use to reach this server, e.g. "mcp.internal.example.com".
const ALLOWED_HOSTS = (process.env.MCP_ALLOWED_HOSTS ?? "localhost,127.0.0.1").split(",");
function buildServer() {
const server = new McpServer({ name: "tickets-api", version: "1.0.0" });
// Register the tools from step 3a here; this one keeps the example short.
server.registerTool(
"ping",
{ description: "Check that the tickets MCP server is reachable", inputSchema: {} },
async () => ({ content: [{ type: "text", text: "pong" }] })
);
return server;
}
function requireToken(req: Request, res: Response, next: NextFunction) {
const got = Buffer.from(req.get("authorization") ?? "");
const want = Buffer.from(`Bearer ${SHARED_TOKEN}`);
if (got.length !== want.length || !timingSafeEqual(got, want)) {
res.status(401).json({ error: "unauthorized" });
return;
}
next();
}
const app = createMcpExpressApp({ host: "0.0.0.0", allowedHosts: ALLOWED_HOSTS });
app.post("/mcp", requireToken, async (req: Request, res: Response) => {
const server = buildServer();
const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined });
res.on("close", () => {
transport.close();
server.close();
});
await server.connect(transport);
await transport.handleRequest(req, res, req.body);
});
app.listen(PORT, "0.0.0.0", () => console.error(`tickets-api MCP on port ${PORT}, path /mcp`));
Python
team_http.py
import hmac
import os
import uvicorn
from mcp.server import MCPServer
from mcp.server.transport_security import TransportSecuritySettings
SHARED_TOKEN = os.environ["MCP_SHARED_TOKEN"]
PORT = int(os.environ.get("PORT", "8000"))
# Host header values clients send, e.g. "mcp.internal.example.com".
ALLOWED_HOSTS = os.environ.get("MCP_ALLOWED_HOSTS", "localhost:*,127.0.0.1:*").split(",")
mcp = MCPServer("tickets-api", version="1.0.0")
# Register the tools from step 3b here; this one keeps the example short.
@mcp.tool()
def ping() -> str:
"""Check that the tickets MCP server is reachable"""
return "pong"
mcp_app = mcp.streamable_http_app(
stateless_http=True,
transport_security=TransportSecuritySettings(allowed_hosts=ALLOWED_HOSTS),
)
async def app(scope, receive, send):
"""Reject HTTP requests without the shared bearer token, then hand off to MCP."""
if scope["type"] == "http":
got = dict(scope["headers"]).get(b"authorization", b"")
if not hmac.compare_digest(got, f"Bearer {SHARED_TOKEN}".encode()):
await send({"type": "http.response.start", "status": 401,
"headers": [(b"content-type", b"application/json")]})
await send({"type": "http.response.body", "body": b'{"error":"unauthorized"}'})
return
await mcp_app(scope, receive, send)
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=PORT)
# Generate the shared token once (openssl rand -hex 32), keep it in a password manager
export MCP_SHARED_TOKEN="paste-the-generated-token"
export MCP_ALLOWED_HOSTS=mcp.internal.example.com
# TypeScript (add express@^5 and @types/express to the step 2 project)
node --import tsx src/team-http.ts
# Python (uvicorn is installed with mcp)
python team_http.py
MCP_ALLOWED_HOSTS must match the Host header the server receives. Behind a reverse proxy that is whatever the proxy forwards (with nginx, add proxy_set_header Host $host;); the Python check also compares the port, so use name:* to allow any port.
Each colleague stores the shared token in an environment variable (here TICKETS_MCP_TOKEN) and references it from their host config instead of pasting it in:
// Cursor (~/.cursor/mcp.json) or VS Code (.vscode/mcp.json, add "type": "http")
{
"mcpServers": {
"tickets": {
"url": "https://mcp.internal.example.com/mcp",
"headers": { "Authorization": "Bearer ${env:TICKETS_MCP_TOKEN}" }
}
}
}
# Claude Code
claude mcp add --transport http tickets https://mcp.internal.example.com/mcp \
--header "Authorization: Bearer $TICKETS_MCP_TOKEN"
# Codex (~/.codex/config.toml)
[mcp_servers.tickets]
url = "https://mcp.internal.example.com/mcp"
bearer_token_env_var = "TICKETS_MCP_TOKEN"
VS Code uses a top-level servers key instead of mcpServers. The MCP config generator writes these entries for each host and converts between JSON and Codex TOML.
What we checked on 2026-10-23 (SDK 1.32.1 with Express 5.3.0 on Node 20, both via tsx and compiled; mcp 2.3.0 on Python 3.13): no token and a wrong token both got HTTP 401; the right token with a Host header that was not in MCP_ALLOWED_HOSTS got 403 (TypeScript) or 421 (Python); the official SDK client with the Authorization header listed and called the tool, and the same client without the header could not connect.
Put the server behind HTTPS (a reverse proxy or your internal load balancer) and keep it on the internal network or VPN. A shared token proves a caller knows the secret, not who they are: everyone gets the same API permissions and audit logs cannot tell people apart. For per-user identity, the MCP authorization specification uses OAuth 2.1, and both SDKs include auth helpers for it. Rotate the shared token when someone leaves the team.
Security checklist for internal APIs
- Use a dedicated, least-privilege token, read-only if you can. The model can call any tool you register, with any arguments it chooses.
- Keep the config file out of git. The token in
envis stored in plain text in that file. - Treat write tools as actions. Claude Desktop and Cursor can ask you to approve each tool call; keep approval on for tools like
add_ticket_commentinstead of auto-running them. - Trim responses. Return only the fields the task needs, and drop personal data the model has no reason to see.
- Never print to stdout. stdout carries the protocol; log with
console.erroror to stderr.
This is a local stdio server: each person runs their own copy with their own token. Sharing one server with a team means switching to Streamable HTTP with a token, as in step 6; the generator does not write that part for you. Parameter types in the form are string, number and boolean; edit the Zod schema or type hints for enums, arrays or objects.
Generate the scaffold for your internal API
List your tools and parameters in the form and download a TypeScript or Python project with the schemas and host config already written. Free, no account, no OpenAPI.
FAQ
How do I turn my existing REST API into an MCP server?
If the API has an OpenAPI spec, paste it into the OpenAPI to MCP converter to get one tool per operation, then trim the list. If it has no spec, or you only want a few tools, generate a stdio scaffold and write each handler as a fetch or httpx call, as in steps 2 to 4 of this guide. Either way, expose task-shaped tools rather than every endpoint.
Do I need an OpenAPI spec to build an MCP server for an internal API?
No. MCP tools are a name, a description and a typed input schema. You define those for the few tasks you want to expose, and each handler calls your API with fetch or httpx. A spec only helps if you want to generate many tools automatically.
Where should the internal API token go?
In the env block of the server entry in claude_desktop_config.json or mcp.json, read by the server with process.env or os.environ. Never make the token a tool parameter, because the model would then see and supply it.
Can a local MCP server reach an API behind a VPN?
Yes. Claude Desktop and Cursor launch the stdio server as a process on your machine, so it uses your machine's network. If the API is only reachable on the VPN, connect the VPN before you start the host.
Why does my Python tool only return "Error executing tool"?
In mcp 2.x only ToolError messages are passed to the model; any other exception is treated as a crash and its text is withheld. Raise ToolError from mcp.server.mcpserver.exceptions with a message that says what failed, such as the HTTP status.
What does the model see if the internal API returns HTML or times out?
Only what your handler returns. In our test an unhandled r.json() on an HTML login page gave the model just Error executing tool get_ticket in Python, and an httpx timeout gave an empty reason. Catch httpx.TimeoutException and ValueError from r.json() and raise ToolError with a clear message, as in the Python file on this page. In TypeScript, return String(err) with isError: true.
Can my whole team share one MCP server for the internal API?
Not with the generated stdio project as it is: each person runs a local copy with their own token. To share one server, switch it to the Streamable HTTP transport and require a bearer token, as in step 6 (tested TypeScript and Python code). Run it behind HTTPS on the internal network; for per-user identity, use OAuth as described in the MCP authorization specification, and check the discovery chain with the OAuth test script before connecting a host.
How does a host send a token to a remote MCP server?
Through an Authorization header in the host config. Cursor and VS Code take a headers object and can read the value from an environment variable with ${env:NAME}; Claude Code takes --header on claude mcp add; Codex reads the token named by bearer_token_env_var in config.toml. Keep the token itself out of the file. Examples are in step 6.