How to Build an MCP Server (and When You Should)

An MCP server is a small program that exposes part of your system to AI applications in a standard way. Building one is an afternoon of work. Deciding whether you should, and how to keep it from becoming a hole in your security, is the harder part. This post covers both: what MCP is, a minimal server you can adapt, when it is the right tool, and what to get right on security and testing.
If the term "agent" is still fuzzy, start with what is an AI agent. MCP is one way an agent gets hands: access to your tools and data. If you are unsure whether you need an agent at all, see AI agent vs chatbot.
What MCP is
The Model Context Protocol (MCP) is an open protocol, introduced by Anthropic, that lets an AI application discover and use capabilities that live somewhere else. Two roles matter:
- The client lives inside the AI application (a chat app, an IDE assistant, your own agent). It connects to servers and passes what they offer to the model.
- The server is a program you write. It exposes capabilities in a standard shape.
A server can offer three kinds of things:
- Tools are functions the model can call, usually with user approval. Example:
get_order_status(orderId). - Resources are data the application or user can read. Example: a policy document, a schema or a file.
- Prompts are reusable prompt templates the user picks. Example: "Summarise this ticket thread".
Most servers start with tools only. Resources and prompts are useful, but you can add them later.
Two transports
A client talks to a server over a transport:
- stdio. The client starts your server as a local child process and talks to it over standard input and output. Simple, no network, good for local tools and for development.
- Streamable HTTP. The server runs as a web service that clients reach over HTTP. This is the choice when several people or applications share one server, and it is where authentication becomes your problem.
One practical trap with stdio: the protocol messages use standard output, so never print logs there. Write logs to standard error.
A minimal server
The sketch below uses the official TypeScript SDK (@modelcontextprotocol/sdk) and zod for input validation. It exposes one read-only tool that looks up an order's status. It is an example to adapt, not production code: check the current SDK docs, because the APIs change between versions.
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: "orders-readonly", version: "0.1.0" });
server.registerTool(
"get_order_status",
{
title: "Get order status",
description:
"Look up the status of ONE order by its ID (format: ORD-12345). " +
"Returns status and expected delivery date. Read-only; cannot change orders.",
inputSchema: {
orderId: z.string().regex(/^ORD-\d{5}$/, "Expected format ORD-12345"),
},
annotations: { readOnlyHint: true },
},
async ({ orderId }) => {
// Replace with a call to your own API, using a read-only credential.
const order = await fetchOrderFromYourApi(orderId);
if (!order) {
return { isError: true, content: [{ type: "text", text: "Order not found." }] };
}
return {
content: [
{
type: "text",
text: JSON.stringify({ status: order.status, eta: order.eta }),
},
],
};
}
);
await server.connect(new StdioServerTransport());
A few details in there are deliberate:
- The description is written for the model. It says what the tool does, the input format and what it cannot do. The model picks tools based on these words.
- Input is validated before anything runs. The model produces the arguments, so treat them like any untrusted input. The regex rejects anything that is not an order ID.
- The tool returns only what the task needs (status and delivery date), not the whole order record with addresses and payment details.
- Errors are returned as tool results (
isError) so the model can react, instead of crashing the server. - The credential behind
fetchOrderFromYourApiis read-only. The strongest guard is the one in the backend, not the one in the prompt.
To try it, point an MCP-capable client at the built server and ask for an order status. The SDK docs also describe an inspector tool for testing a server without a model in the loop.
When you should build one, and when you should not
An MCP server is an interface, and interfaces cost maintenance. It earns its place in some situations and not in others.
| Situation | Better choice |
|---|---|
| One application, a handful of tools, you own the code | Plain function calling inside that app |
| Several agents or AI clients need the same internal system | MCP server |
| You want one place to enforce permissions, limits and logging for AI access | MCP server |
| The tool is just a call to an existing, well-documented REST API | Wrap the API in a function; MCP only if others will reuse it |
| Users want to plug your system into AI apps they already use | MCP server |
| A fixed rule or script does the job without a model | Neither; use classic automation |
The deciding question is reuse and boundary. If one agent in one codebase needs three tools, a function call is less code and fewer moving parts. If the same internal system must be reachable by a support agent, a coding assistant and a reporting agent, an MCP server gives them one door, and gives you one place to decide what that door allows.
For the wider picture of where agents help and where they do not, see AI agents for business use cases and limits and the examples in agentic AI examples for SMEs.
Security: treat the server as a permission boundary
The point of an MCP server is a clean boundary between a model and your systems. That only works if you design it as one.
- Least privilege. Each tool does one narrow thing. Prefer
get_order_statusoverrun_sql. Give the server's credential only the rights those tools need. - Read-only by default. Start with tools that cannot change anything. Add write tools one at a time, deliberately.
- Confirm destructive actions. Anything that deletes, pays, sends or publishes needs a human approval step, enforced by the client or by a two-step flow in the server (propose, then confirm).
- Never trust tool output or resource text as instructions. A web page, email or document that a tool returns can contain text written to manipulate the model (prompt injection). Treat returned content as data. Keep powerful tools away from sessions that also read untrusted content, or require approval when they meet.
- Secrets stay outside the model. API keys live in the server's environment or a secrets manager. They are never passed as tool arguments, returned in results or written to logs.
- Per-user authentication for remote servers. A shared HTTP server must know who is calling and apply that person's permissions, not one all-powerful service account. The MCP specification includes an authorisation part built on OAuth; read the current version before implementing it.
- Audit logs. Record who called which tool with which arguments and what came back, so you can answer "what did the agent do?" later.
- Rate limits and size limits. Cap calls per minute and result sizes. A confused loop should hit a limit, not your database.
Also be careful with third-party servers you install. A server is code that runs with your permissions; read it and pin versions before connecting it to anything sensitive. We cover the wider set of agent guardrails in a follow-up post.
Evaluation: does the model use it correctly?
A server that works in a demo can still fail in real use, because the model has to choose the right tool and fill in the arguments. Test that, not only the code.
- Tool descriptions. Most failures trace back to vague names and descriptions. Say what the tool is for, what each argument means, and when not to use it. If two tools overlap, merge them or make the difference explicit.
- Golden tasks. Write 15 to 30 realistic requests with a known correct outcome ("What is the status of ORD-10234?", plus awkward ones: a missing ID, a typo, a request outside the tool's scope). Run them after every change and record whether the right tool was called with the right arguments.
- Trace review. Read the actual sequences of calls. Look for wrong tool choices, repeated retries, oversized results and cases where the model should have stopped and asked. Fix descriptions and error messages first; they are the cheapest lever.
- Negative cases. Include attempts that should fail: an invalid ID, a request for data the tool must not return, a document containing an injected instruction. The expected outcome is a refusal or an error, not a clever workaround.
Related reading: AI agent guardrails and evaluation.
FAQ
What is an MCP server in simple terms? A program that exposes tools, readable resources and prompt templates to AI applications through a standard protocol. The AI application (the client) discovers what is available and calls it, so you write the integration once instead of once per application.
Do I need an MCP server to build an AI agent? No. An agent can call plain functions or APIs directly. MCP helps when several agents or AI applications must share the same tools, or when you want a single, controlled boundary around an internal system.
Is it safe to expose my internal systems through MCP? It can be, if you design for it: narrow read-only tools first, a least-privilege credential, confirmation for destructive actions, per-user authentication on remote servers, audit logs and limits. Treat everything the server returns as untrusted data, never as instructions.
Planning your agent's tool layer
Deciding which systems an agent may touch, with which permissions, and how to test it is the real work behind a useful agent. We help teams scope that and build it with approvals and logging from day one. Read how we approach AI agent development and get in touch with the system you want to connect.
Have a project idea?
Get a rough estimate in 5 minutes with our Project Scoper.
Scope Your ProjectReady to discuss?
30 minutes. No pitch deck. Just an honest conversation about your project.
Book a Free Call





