Every internal tooling request follows the same arc. An engineer pastes a redacted stack trace into a chat window, the model asks for the staging row that produced it, and everyone waits while somebody with database access copies the answer by hand. Multiply that by a dozen people and the assistant that was supposed to save time becomes a queue.
The fix is not a longer prompt. MCP server development for custom internal tools is the work of giving the assistant a scoped, read-only window into the one internal system it needs, running with the same permissions as the person asking and writing an audit record for every call.
The Model Context Protocol (MCP) is the open JSON-RPC 2.0 standard that makes this portable across Claude Desktop, Cursor, VS Code extensions, and anything else that implements the client side. This page covers building one in TypeScript against the current protocol revision, the transport choices that break in production, the security boundaries that stop an AI agent from becoming an unauthenticated database client, and the failure modes we hit when rolling these out to engineering teams.
For the client half of the same system, see the MCP client implementation guide. For the threat model around tool descriptions, read MCP server security hardening. If you only need to attach an existing server to your editor, installing MCP servers in VS Code covers that path. Business owners weighing whether to adopt the protocol at all should start with what MCP means for a small business.
Start With One Tool, Not a Platform
The failure pattern I see most often is a team building one internal server that exposes the bug tracker, the database, the deploy pipeline, and the metrics API in a single process. It demos well and it is impossible to review. Every tool in that server is reachable by every client, the permission surface is the union of everything, and one bad tool description contaminates the whole catalogue.
Pick one friction point that satisfies three tests:
- Narrow read. The tool answers a question with a bounded result: one order, one ticket, the last twenty log lines for a correlation ID.
- Stated query. You can write the exact SQL or the exact endpoint and method, and put it in a code review.
- Repeatable demand. Three or more people ask for the same lookup every week. If it is rare, a saved query beats a server.
A first server with two tools is normal. A first server with fifteen tools usually means the scope was wrong.
What the Protocol Actually Specifies
MCP is a JSON-RPC 2.0 conversation between a host application (the AI client) and a server. The server advertises three primitive types:
- Tools are callable functions the model can invoke with structured arguments. This is what exposes internal data.
- Resources are readable payloads addressed by URI, which the host can attach to a conversation as context.
- Prompts are parameterized templates the host surfaces as commands, such as a postmortem skeleton that pulls incident fields.
The lifecycle is short. The client opens a session and both sides exchange capabilities. The client calls tools/list and receives each tool's name, description, and inputSchema as plain JSON Schema. When the model decides to call a tool, the client sends tools/call with a name and arguments, and the server returns content blocks plus an optional error flag. There is no model inside the server and no prompt inside the server. The server is a typed data access layer that happens to be called by an LLM.
That last point has a practical consequence: JSON Schema quality determines tool reliability more than anything else in the code. A parameter described as "the order" will be filled with a customer name. A parameter described as "internal order identifier in the format ORD-9912, digits only" with a regex constraint gets filled correctly.
What Transport Protocol Should You Choose Between stdio and Streamable HTTP?
Two transports matter. Pick by where the server runs, not by preference.
stdio keeps the server on the same machine as the client. The host spawns it as a child process and exchanges JSON-RPC over stdin and stdout. There are no ports, no CORS, no TLS certificates, and no shared credentials: the process inherits the permissions of the developer who started it, and it exits when the editor does. This is the right default for desktop assistants reaching a local checkout, a local SQLite file, or a Docker container on localhost.
One rule is non-negotiable: never write diagnostics to stdout in a stdio server. A single console.log("connected") inserts non-JSON text into the frame stream and every subsequent message fails to parse. The client will report a parse error, not "your log statement broke the transport", which is why this wastes an afternoon. Route all diagnostics to console.error, which writes to stderr and is ignored by the protocol.
Streamable HTTP runs the server as a separate process or container and exposes one HTTP endpoint that accepts POST. Each JSON-RPC message is its own POST, and the server answers either with a JSON object or with an SSE stream scoped to that request. This is the transport to use when several engineers share one staging replica and you cannot distribute database credentials to every laptop.
Two things changed recently enough that older tutorials are now wrong:
- The original HTTP+SSE transport is deprecated. It was superseded in the 2025-03-26 revision and is on the removal path. Servers that still expose the 2024-11-05 shape do so for old clients only.
- The 2026-07-28 revision removed the GET stream endpoint and protocol-level sessions. There is no
Mcp-Session-Idto manage and no long-lived GET stream for server-initiated messages. Change notifications are delivered through asubscriptions/listenrequest, and closing the response stream is the cancellation signal.
The current revision also requires the client to mirror routing fields into headers. Every POST carries MCP-Protocol-Version, Mcp-Method, and Mcp-Name, and a server that processes the body must reject requests where those headers disagree with the body, returning 400 with a HeaderMismatch error. That rule exists for exactly the reason you would expect: a load balancer that routes by header and a server that executes by body are two sources of truth, and the gap between them is an authorization bug.
If you are on an integration framework, @modelcontextprotocol/express, @modelcontextprotocol/hono, and @modelcontextprotocol/fastify handle the header validation, origin checks, and session-free request handling for you. Writing the transport by hand is a week of avoidable work.
How Do You Secure Internal Credentials Inside Custom MCP Servers?
An MCP server is a privileged bridge into a private network. Assume the model will eventually be talked into calling the wrong tool with the wrong arguments, because it will.
1. Read-only at the database, not in the prompt. Provision a dedicated role with GRANT SELECT on the specific tables and connect through a read replica. Never rely on the tool implementation to remember to avoid writes, and never reuse an application role that can delete. A query that reaches production because the model constructed a plausible table name is an instant incident.
2. Caps belong in code. Enforce a row limit, a statement timeout, and a response size ceiling in the handler. A model cannot be trusted to include LIMIT, and one unbounded select * from an events table will either time out the replica or return a megabyte of JSON that costs real money to put in a context window.
3. Credentials come from the environment. Connection strings and API tokens belong in a local .env file or a secret manager, never in source and never in a client configuration file that gets synced to a personal cloud drive. The client config should hold a command, not a password.
4. Tool output is untrusted input to the model. This is the part most internal builds skip. A staging row can contain a customer note, a log line, or a branch name written by anyone. If a tool returns text that reads like instructions, the model may follow it. The defence is structural: never let a tool return data that provisions another tool, keep destructive tools out of the catalogue entirely, and keep the write path behind a human approval step that does not involve the model.
For the HTTP transport, add origin validation to the checklist. Without an origin check and authentication, a page in a browser can reach a local server through DNS rebinding, and the specification treats that as a required control rather than a suggestion.
Every call should leave an audit record. This is the schema we log, and it is enough to reconstruct who asked for what:
{ "mcp_server_audit_event": { "timestamp": "2026-11-15T18:40:12Z", "server": "internal-order-tools@1.2.0", "client_id": "claude-desktop-macos", "user": "jane.dev@example.org", "tool_invoked": "get_order_details", "arguments_hash": "sha256:7f4c1b0e", "db_query_duration_ms": 14.2, "rows_returned": 3, "payload_bytes": 1240, "status": "SUCCESS" } } Log the argument hash, not the argument, so customer identifiers do not accumulate in a log index.
How Do You Build a Custom MCP Server for Internal Developer Tools?
The TypeScript SDK moved to split packages in v2: @modelcontextprotocol/server for servers, @modelcontextprotocol/client for clients, and transport entry points under each. The v1 layout (@modelcontextprotocol/sdk/server/index.js) still exists for existing code and has a published codemod migration, but new servers should start on v2 entry points.
Step 1: Register One Typed, Read-Only Tool
This server exposes one read-only tool over stdio, with parameter validation, a row cap, a statement timeout, truncation, and structured errors:
import { McpServer } from "@modelcontextprotocol/server"; import { StdioServerTransport } from "@modelcontextprotocol/server/stdio"; import * as z from "zod/v4"; import { Pool } from "pg"; const pool = new Pool({ connectionString: process.env.STAGING_DATABASE_URL, max: 4, statement_timeout: 5000, application_name: "mcp-internal-order-tools", }); const MAX_ITEMS = 25; const MAX_CHARS = 8000; const server = new McpServer({ name: "internal-order-tools", version: "1.2.0" }); server.registerTool( "get_order_details", { description: "Read staging order metadata for a single internal order ID. Read only, returns at most 25 line items.", inputSchema: z.object({ orderId: z .string() .regex(/^ORD-\d{4,8}$/) .describe("Internal order identifier, for example ORD-9912"), }), }, async ({ orderId }) => { const started = Date.now(); try { // Read replica, parameterized, capped, and bounded by statement_timeout. const { rows } = await pool.query( `select o.id, o.status, o.total_cents, o.updated_at, (select json_agg(i) from (select sku, qty, unit_price_cents from order_items where order_id = o.id order by sku limit $2) i) as items from orders o where o.id = $1`, [orderId, MAX_ITEMS] ); if (rows.length === 0) { return { content: [{ type: "text", text: `No order found for ${orderId}.` }] }; } let text = JSON.stringify(rows[0], null, 2); if (text.length > MAX_CHARS) { text = text.slice(0, MAX_CHARS) + "\n[truncated at 8000 characters]"; } console.error(`get_order_details ok order=${orderId} ms=${Date.now() - started}`); return { content: [{ type: "text", text }] }; } catch (error) { // Errors are data, not crashes. The model gets a reason it can act on. console.error(`get_order_details failed order=${orderId}`, error); return { isError: true, content: [{ type: "text", text: `Lookup failed: ${(error as Error).message}` }], }; } } ); async function main() { await server.connect(new StdioServerTransport()); console.error("internal-order-tools ready on stdio"); } main().catch((error) => { console.error("fatal startup error", error); process.exit(1); }); Two details in that listing carry most of the safety. The Zod schema rejects anything that is not shaped like an internal order ID before a query runs, so neither SQL injection nor a hallucinated identifier reaches the database. And the try block returns isError: true with a message instead of throwing, which keeps the transport alive and gives the model a chance to correct its arguments rather than lose the session.
Step 2: Wire It Into the Client by Command
Register the server in the client configuration by command, with the secret referenced from the environment:
{ "mcpServers": { "internal-order-tools": { "command": "npx", "args": ["-y", "@your-org/mcp-internal-tools@1.2.0"], "env": { "STAGING_DATABASE_URL": "${env:STAGING_READONLY_URL}" } } } } Test the Protocol Before Your Team Does
Tool handlers are ordinary functions, so test them as ordinary functions. The part that breaks in production is the protocol conversation, and that is testable too.
Start a real server process and talk to it with the client SDK:
import { Client } from "@modelcontextprotocol/client"; import { StdioClientTransport } from "@modelcontextprotocol/client/stdio"; const client = new Client({ name: "smoke-test", version: "1.0.0" }); await client.connect( new StdioClientTransport({ command: "node", args: ["dist/server.js"] }) ); const { tools } = await client.listTools(); const tool = tools.find((t) => t.name === "get_order_details"); if (!tool || !tool.inputSchema.properties?.orderId) { throw new Error("tool schema regressed"); } const good = await client.callTool({ name: "get_order_details", arguments: { orderId: "ORD-9912" }, }); if (!Array.isArray(good.content)) throw new Error("unexpected content shape"); const bad = await client.callTool({ name: "get_order_details", arguments: { orderId: "'; drop table orders; --" }, }); if (!bad.isError) throw new Error("validation did not reject malformed input"); Run that in CI on every pull request that touches a tool definition. It catches the three regressions that matter: a schema change that breaks the client, a validation rule that silently loosens, and a transport that starts writing to stdout. A handler-level unit test with a fake pool covers the SQL, and the protocol smoke test covers everything the handler cannot see.
Five Failure Modes We Hit in Production
| Symptom | Cause | Fix |
|---|---|---|
| Client reports a parse error on every message after connect | A console.log in the server wrote to stdout | Move all diagnostics to console.error |
| Tool call costs jump and answers degrade | Unbounded result sets flooding the context window | Row cap, character cap, and truncation marker |
| Model calls the same tool repeatedly with the same arguments | No error signal, so it retries instead of adapting | Return isError with a corrective message |
| Server works until the internal API ships a rename | No contract test on the queried columns | Schema assertion in CI against a staging database |
| Credentials appear in a screenshot of someone's config | Secret stored in the client JSON | Reference an environment variable or secret manager |
The context-window failure deserves a number, because it is the one that quietly costs money. A single row of order JSON is roughly 60 to 90 tokens once formatted. Twenty-five rows is about 2,000 tokens, which is fine. A thousand rows is 80,000 tokens of tool output, and tool results are re-sent on every subsequent turn of the same conversation. A five-turn debugging session against that response burns a few hundred thousand input tokens for one lookup.
Rolling It Out in Four Phases
- Scope and provision. Pick the one question worth automating, create a read-only role against a replica, and write down the exact query in the pull request description.
- Prototype locally over stdio. Ship it as an
npxpackage so the client config stays one line, test the tool with real arguments from a real incident, and verify stdout carries nothing but JSON-RPC. - Centralize and isolate. Move to a private registry or container image, inject secrets from the secret manager at runtime, and add response size limits before the third tool ships.
- Instrument and prune. Log every invocation with duration and payload size, rate limit the expensive tools, and delete tools nobody called in a quarter. A catalogue that only grows is a permission surface that only grows.
Conclusion
An MCP server is not a chatbot feature. It is a data access layer with a model as one of its callers, which means the engineering discipline that applies to any privileged service applies here: narrow scope, parameterized queries, read-only credentials, hard caps on payload size, and an audit trail that survives an incident review.
Get those right and the assistant stops being a queue for whoever holds database credentials. Get them wrong and you have connected a language model directly to your staging data with no more protection than a prompt asking it to behave.
<span> AI Tooling & MCP Engineering </span> <h3> Ready to build custom MCP servers for your engineering team? </h3> <p> Veduis helps software engineering teams build, secure, and deploy custom Model Context Protocol servers connecting AI desktop assistants to internal infrastructure. </p> <a href="https://veduis.com/contact/"> Consult an MCP Specialist </a> 



