Skip to main content

MCP Servers Explained: Build, Connect, and Secure Them (2026 Guide)

By Pashalis LaoutarisUpdated: Category: AI & LLM Development26 min read

Every AI assistant eventually hits the same wall. It can write code and answer questions, but it cannot see your database, your tickets, or your files unless someone wires those in. For years, each wiring job was custom work, repeated for every app and every model.

The Model Context Protocol, or MCP, is the attempt to end that repetition. You write one server that exposes your data or actions. Any MCP-aware client can then use it. Think of it as a USB port for AI tools, with all the convenience and all the risk that comes with plugging unknown devices into your machine.

This guide explains MCP in plain terms, then builds real servers. I ran both server examples. The TypeScript server runs against the @modelcontextprotocol/server 2.4.0 package, and the Python one runs against mcp 2.3.0. I connected to each with a test client and checked the results. I did not make live calls to the Anthropic API, and I did not test every client mentioned. Each section says what I verified.

The protocol facts come from the official MCP specification, version 2026-07-28, which I read on November 19, 2026. It pairs with my guides to Claude Code, AI-powered IDEs, and secrets management, because an MCP server is a place where all three topics meet.

Table of Contents

  1. The Short Answer
  2. What MCP Is and Is Not
  3. The Building Blocks
  4. How the 2026-07-28 Protocol Works
  5. Build a Server in TypeScript
  6. Build a Server in Python
  7. Test Before You Trust
  8. Connect Servers to Clients
  9. Authorization for Remote Servers
  10. Security: What Has Gone Wrong
  11. Designing Tools Models Can Use
  12. Registry and Governance
  13. Common Mistakes
  14. Frequently Asked Questions
  15. Conclusion
  16. References

1. The Short Answer

MCP is an open protocol that lets AI applications discover and call tools, read data, and use prompt templates from separate programs called servers. It uses JSON-RPC messages over either a local pipe (stdio) or HTTP.

If you want to… Do this
Give an assistant access to your own tools Write a small MCP server, start with the stdio transport, and use the official SDK.
Use someone else’s integration Prefer an official server from the vendor. Read what it does and what access it needs before connecting.
Share a server with a team Host it over Streamable HTTP, add OAuth, and apply least-privilege scopes.
Call an MCP server from your own app Use the SDK client, or the MCP connector in the Anthropic Messages API for remote servers.
Reduce risk Treat every server as code that runs with your privileges, and treat every tool result as untrusted.

Three rules cover most of the value.

  • Start local and small: A stdio server with two tools teaches you the whole model in an afternoon.
  • Write for the model, not the human: Clear tool names, short descriptions, and actionable error messages matter more than clever code.
  • Assume the server is hostile until proven otherwise: Most real incidents so far came from trusting a package or a connection too quickly.

2. What MCP Is and Is Not

MCP standardizes the conversation between an AI application and the things it can use. Anthropic created it, and it has since moved to neutral governance, which section 12 covers.

What MCP is, in practice:

  • A specification for how clients list tools, call them, read resources, and fetch prompts.
  • A set of official SDKs, including TypeScript and Python.
  • A set of transports for local and remote use.

What it is not:

  • It is not a model API. MCP does not generate text. It only moves context and actions between a client and a server.
  • It is not a security boundary by itself. The protocol describes good practice, but each client and server decides how strictly to follow it.
  • It is not the only way to give a model tools. Native function calling, such as the tool use feature in the Anthropic API, still works fine when you control both sides.

The real benefit appears when you do not control both sides. A vendor ships one server, and every compliant client can use it. That is the same bargain the Language Server Protocol struck for editors, and it is why MCP spread quickly through AI-powered IDEs and tools like VS Code.

3. The Building Blocks

An MCP setup has three roles.

  • Host: The application the user talks to, such as Claude Code or an IDE.
  • Client: The part of the host that holds one connection to one server.
  • Server: The program that exposes capabilities.

Servers offer three main kinds of capability.

Capability Who controls it What it is
Tools The model Functions the model can decide to call, such as “search tickets” or “run a query”.
Resources The application Readable data identified by a URI, such as a file or a database row.
Prompts The user Reusable prompt templates the user picks explicitly.

Tools get most of the attention, and they carry most of the risk. The specification says that for trust and safety there should always be a human in the loop with the ability to deny tool calls. It also says clients must treat tool annotations as untrusted unless they come from a trusted server.

A tool definition has a name, an optional title, a description, an inputSchema written in JSON Schema, and an optional outputSchema. Results can return text, images, audio, links to resources, or embedded resources. A result can also carry structuredContent, which is plain JSON that matches the output schema.

4. How the 2026-07-28 Protocol Works

If you read older MCP tutorials, some of what they say is out of date. The 2026-07-28 revision changed the shape of the protocol. These are the changes that matter most to builders, taken from the official changelog.

It is stateless now. The old initialize handshake is gone. Every request carries its protocol version and client capabilities in a _meta field. Servers can identify themselves in each result’s _meta too. If versions do not match, the server returns an UnsupportedProtocolVersionError.

Protocol sessions are gone. The Streamable HTTP transport no longer uses the Mcp-Session-Id header. Tool lists no longer vary per connection. A server that needs state across calls returns an explicit handle, such as a basket ID, and receives it back as an ordinary tool argument.

There is a discovery call. Servers must implement server/discover, which reports supported protocol versions, capabilities, and identity. Clients can call it first to pick a version, or use it to probe older servers on stdio.

Results say what they are. Every result has a required resultType field. The value is complete for normal results and input_required when the server needs more information from the user.

Servers ask for input differently. A pattern called multi round-trip requests replaces server-initiated requests. The server returns an input_required result that lists what it needs. The client gathers the answers and retries the original request with them attached.

Change notifications use one stream. A single subscriptions/listen call replaces the old GET endpoint and the subscribe calls. Clients opt in to the change types they want.

Caching is built in. Results from list calls must now carry ttlMs and cacheScope fields. Servers should also return tools in a deterministic order, which helps both client caches and model prompt caches.

Long-running work moved to an extension. Tasks left the core protocol and became an official extension, io.modelcontextprotocol/tasks. Both client and server capabilities now have an extensions field for this kind of optional feature.

Several features are deprecated. The specification marks Roots, Sampling, and Logging as deprecated, along with the older HTTP+SSE transport. It also deprecates OAuth Dynamic Client Registration in favor of Client ID Metadata Documents. Deprecated features keep working for a window of at least twelve months, so new code should avoid them.

Transport choices are simple. Two transports remain current. Stdio runs the server as a child process of the client. Streamable HTTP serves requests over HTTP POST and fits remote and shared servers. For stdio servers, the specification’s guidance matches common sense: write logs to stderr, never to stdout, because stdout carries the protocol messages.

5. Build a Server in TypeScript

This server has two tools. One counts words and returns structured output. The other divides two numbers and returns a helpful error on division by zero.

Set up the project.

mkdir text-tools && cd text-tools
npm init -y
npm install @modelcontextprotocol/server zod
npm install -D typescript @types/node

Set "type": "module" in package.json. Use a tsconfig.json with target ES2022, module and moduleResolution set to Node16, and strict on. Then write the server in src/server.ts.

import { McpServer } from "@modelcontextprotocol/server";
import { serveStdio } from "@modelcontextprotocol/server/stdio";
import { z } from "zod";

function createServer() {
  const server = new McpServer({ name: "text-tools", version: "1.0.0" });

  server.registerTool(
    "word_count",
    {
      title: "Word counter",
      description: "Count the words and characters in a piece of text.",
      inputSchema: z.object({
        text: z.string().min(1).describe("The text to analyze"),
      }),
      outputSchema: z.object({ words: z.number(), characters: z.number() }),
    },
    async ({ text }) => {
      const result = {
        words: text.trim().split(/\s+/).length,
        characters: text.length,
      };
      return {
        content: [{ type: "text", text: JSON.stringify(result) }],
        structuredContent: result,
      };
    },
  );

  server.registerTool(
    "divide",
    {
      description: "Divide one number by another.",
      inputSchema: z.object({ a: z.number(), b: z.number() }),
    },
    async ({ a, b }) => {
      if (b === 0) {
        return {
          content: [
            {
              type: "text",
              text: "Cannot divide by zero. Pass a non-zero value for b.",
            },
          ],
          isError: true,
        };
      }
      return { content: [{ type: "text", text: String(a / b) }] };
    },
  );

  return server;
}

serveStdio(createServer, {
  onerror: (error) => console.error("text-tools error:", error),
});
console.error("text-tools MCP server running on stdio");

Compile with npx tsc, which writes build/server.js.

A few details are worth noticing.

  • Logs go to console.error: Writing to console.log would corrupt the protocol stream on stdio.
  • Schemas come from Zod: The SDK turns them into the JSON Schema that clients see.
  • Errors are results: The divide tool returns isError: true with a message the model can act on. The specification calls this a tool execution error, and clients should show it to the model so it can correct itself.
  • Protocol errors are different: An unknown tool name or a malformed request produces a JSON-RPC error instead.

What I tested: I wrote a client with the @modelcontextprotocol/client package that launches this server over stdio. It listed both tools. Calling word_count with “one two three” returned {"words":3,"characters":13} as structured content. Calling divide with a zero divisor returned the error flag set to true. I ran the client in both of its version-negotiation modes, auto and legacy, and got the same results each time.

6. Build a Server in Python

The Python SDK keeps things shorter. It uses decorators and reads types and docstrings to build the schemas.

python -m venv .venv
.venv/Scripts/pip install mcp

On macOS or Linux, use .venv/bin/pip instead. Then write the server in server.py.

from mcp.server import MCPServer
from mcp.server.mcpserver.exceptions import ToolError

mcp = MCPServer("text-tools-py")


@mcp.tool()
def word_count(text: str) -> dict:
    """Count the words and characters in a piece of text."""
    return {"words": len(text.split()), "characters": len(text)}


@mcp.tool()
def divide(a: float, b: float) -> float:
    """Divide one number by another."""
    if b == 0:
        raise ToolError("Cannot divide by zero. Pass a non-zero value for b.")
    return a / b


@mcp.resource("notes://{topic}")
def note(topic: str) -> str:
    """Return a canned note about a topic."""
    return f"Notes about {topic}: nothing written yet."


if __name__ == "__main__":
    mcp.run()

One trap I hit: My first version raised a plain ValueError for the zero case. The client got only a generic “Error executing tool divide” message, and the server printed a noisy failure log. Raising ToolError fixed it, because that message reaches the model intact. If your tool’s errors are vague, the model cannot recover from them.

What I tested: With mcp 2.3.0, a test client launched the server over stdio. The word_count call returned the counts as JSON text, with resultType set to complete and the server name in the result’s _meta. The zero-divisor call returned isError: true with the message above. I did not test reading the notes:// resource, so treat that part as untried.

7. Test Before You Trust

You need two kinds of testing: checking that your server works, and checking that you trust what you plug in.

Test your own server. Write a small script with the SDK client, as I did, and assert on the tool list and a few calls. This catches schema mistakes and stdout pollution early. There is also an official debugging tool, the MCP Inspector. According to its README, npx @modelcontextprotocol/inspector starts a web UI, and --cli and --tui flags give a command-line client and a terminal UI. I did not launch it for this article. The README points to a separate configuration guide for connecting servers, so read that before relying on a specific command. It also lists a Node version requirement, ^22.23.4 || ^24.22.1 || >=26.12.1, so check yours.

The Inspector has had its own security history, which section 10 covers. It also stores secrets such as OAuth tokens. By default it uses the operating system keychain. When no keychain exists, such as on a headless machine or in a container, it writes them to ~/.mcp-inspector/secrets.json without encryption. Keep that in mind on shared machines.

Test servers you did not write. Before connecting a third-party server, check who publishes it, read its source or at least its tool list, and note which credentials it needs. My guides to dependency scanning and supply chain security apply here without changes, because an npx server is just an npm package that runs on your machine.

8. Connect Servers to Clients

Claude Code

I checked these commands against the official Claude Code documentation. To add a remote server, use the HTTP transport.

claude mcp add --transport http notion https://mcp.notion.com/mcp

To add a local stdio server, put the command after a double dash. The dash separator is required.

claude mcp add --transport stdio text-tools -- node C:/path/to/text-tools/build/server.js

Servers have three scopes. The default is local, which applies to the current project only and is stored in your user config file. The project scope writes a .mcp.json file in the project root so a team can share it through version control. The user scope applies to all your projects.

A project-scoped stdio server looks like this in .mcp.json.

{
  "mcpServers": {
    "database-tools": {
      "command": "npx",
      "args": ["-y", "some-db-mcp-server"],
      "env": { "DB_URL": "${DB_URL}" }
    }
  }
}

Environment variables can be referenced as ${VAR}. That keeps secrets out of the file you commit. Claude Code asks for approval before using project-scoped servers from .mcp.json in interactive sessions, which protects you when you clone a repository you do not fully trust. You can list servers with claude mcp list, inspect one with claude mcp get, and remove one with claude mcp remove. Inside a session, /mcp shows status and handles sign-in.

The documentation carries a warning I would repeat: verify that you trust each server, because servers that fetch external content can expose you to prompt injection. My Claude Code deep dive covers permissions and hooks that help limit the damage.

The Anthropic API

If you build your own application on the Claude API, the Messages API has an MCP connector for remote servers. You pass the server details and also enable its tools. Both halves are required, and the request is rejected with only one.

import Anthropic from "@anthropic-ai/sdk";

const client = new Anthropic();

const response = await client.beta.messages.create({
  model: "claude-opus-5-5",
  max_tokens: 16000,
  betas: ["mcp-client-2025-11-20"],
  mcp_servers: [
    { type: "url", url: "https://example.com/mcp", name: "example" },
  ],
  tools: [{ type: "mcp_toolset", mcp_server_name: "example" }],
  messages: [
    { role: "user", content: "What can the example server do for me?" },
  ],
});

I took this shape from Anthropic’s API reference material and did not run it, because I made no live API calls for this article. Check the current MCP connector documentation for authentication options, platform availability, and limits before you build on it. The connector reaches remote servers over HTTP, so a local stdio server needs the SDK client path or a client such as Claude Code instead.

Other clients

I confirmed Claude Code and the Anthropic API against primary documentation. For other clients, I relied on secondary coverage and did not verify it against vendor docs this time. That coverage says the OpenAI Responses API supports remote MCP servers, Cursor reads an mcp.json file, and Copilot supports MCP through VS Code. Support in other products changes quickly, so check each vendor’s current documentation before you plan around it.

9. Authorization for Remote Servers

A local stdio server inherits the trust of your machine. A remote server needs real authentication, and the specification builds it on OAuth. These are the points builders most often miss.

  • Tokens must be meant for your server: Servers must not accept tokens issued for any other resource. Forwarding a client’s token to a downstream API, known as token passthrough, is explicitly forbidden.
  • Client registration is changing: Client ID Metadata Documents are now the preferred way for clients to identify themselves. Dynamic Client Registration is deprecated but remains available for older authorization servers.
  • Validate the issuer: Authorization servers should include an iss parameter in responses, and clients must check a present iss before redeeming the code. This defends against mix-up attacks.
  • Credentials belong to one issuer: Clients must key stored credentials by the issuer and must re-register when the authorization server changes.
  • Ask for the least privilege: Start with a small scope set and step up through WWW-Authenticate challenges when a sensitive operation needs more. Avoid wildcard scopes such as * or full-access.

If you run a proxy-style server that fronts a third-party API with one static client ID, read the confused deputy section of the security best practices page. It requires per-client consent, exact redirect URI matching, and careful handling of the OAuth state parameter. This is subtle work. Use an established identity provider and a maintained library instead of writing your own flow.

10. Security: What Has Gone Wrong

MCP is young, and the incidents so far fall into three groups: malicious packages, flawed tooling, and protocol-level attack patterns.

Malicious and impersonated servers

In September 2025, researchers at Koi Security reported that an npm package called postmark-mcp had turned malicious. Version 1.0.16 added a single line that copied every outgoing email to an address controlled by the attacker. The package copied a legitimate project maintained by ActiveCampaign, which said it had nothing to do with the copy. Estimates of the damage vary between sources, so I will not quote a number. The lesson is simple. An MCP server that sends email can read and forward your email, and a package name does not prove who published it.

Flawed tooling

Two critical advisories hit popular MCP tools in 2025.

  • MCP Inspector: GitHub advisory GHSA-7f8r-222p-6f5g, tracked as CVE-2025-49596, describes missing authentication between the Inspector client and its proxy. Versions below 0.14.1 are affected, and 0.14.1 contains the fix.
  • mcp-remote: GitHub advisory GHSA-6xpm-ggf7-wc3p, tracked as CVE-2025-6514, covers operating system command injection through untrusted server connections. It carries a CVSS score of 9.6. Versions from 0.0.5 up to but not including 0.1.16 are affected, and 0.1.16 is the fixed release.

Both involve a tool that sits between you and a server, so keep such tools updated. The second one also shows why connecting to an unknown remote server is not harmless, because the connection itself can be an attack surface.

Protocol-level attack patterns

The official security best practices page covers these in detail.

Attack What happens Main defense
Confused deputy A proxy server’s static client ID and a consent cookie let an attacker skip user consent. Per-client consent, exact redirect URI matching, protected state values.
Token passthrough A server accepts or forwards tokens that were not issued for it. Reject any token not issued to your server.
SSRF during OAuth discovery A malicious server points the client at internal addresses or cloud metadata endpoints. Require HTTPS, block private ranges, validate redirects, use egress proxies.
State handle hijacking An attacker guesses a handle a server minted and acts on someone else’s state. Random handles, bound to the authenticated user, verified on every call.
Local server compromise A malicious start-up command or package runs with the client’s privileges. Show the exact command, require consent, sandbox the process.
Malicious authorization URLs A javascript: URL or shell injection runs code inside a client. Allow only http and https, and never open URLs through a shell.
Scope inflation A broad token is stolen and opens every tool. Minimal scopes with step-up elevation.

Prompt injection through tool results

There is one more risk that no protocol rule can remove. A tool that reads web pages, tickets, or emails returns text that someone else wrote. That text can contain instructions aimed at the model. The model cannot reliably tell your instructions from the ones hidden in the data.

Practical defenses to apply:

  • Give each server the least access it needs, and prefer read-only credentials.
  • Keep a human approval step on any action that sends, deletes, pays, or publishes.
  • Avoid combining a server that reads untrusted content with one that can send data out, in the same session.
  • Log tool calls so you can review what happened.

My secrets management guide explains how to keep the credentials these servers use out of config files and shell history. The Gitleaks article shows how to catch a token that slips into a repository anyway.

11. Designing Tools Models Can Use

A tool is an interface for a model, and models read descriptions the way new teammates read documentation. Good design makes the difference between a tool that gets used correctly and one that gets misused.

  • Name tools by task: search_tickets beats query. Names may use letters, digits, underscores, hyphens, and dots, up to 128 characters.
  • Write one clear description: Say what the tool does, when to use it, and what it returns. Mention limits, such as “returns at most 20 results”.
  • Keep inputs small and typed: Use enums and descriptions on each field. Avoid free-form blobs when a few fields would do.
  • Return errors the model can act on: “Invalid departure date: must be in the future” teaches the model to retry. “Error 500” does not.
  • Prefer fewer, sharper tools: Every tool definition costs context tokens. Dozens of overlapping tools make selection worse and the bill higher.
  • Keep the tool list stable: The specification asks servers to return tools in a deterministic order, which lets clients cache the list and helps prompt caching.
  • Separate read and write: Make destructive actions their own tools, so clients can ask for approval on exactly those.
  • Design stateful tools with explicit handles: If a workflow needs a basket or a transaction, return an opaque, random handle and check ownership on every call. State the handle’s lifetime in the tool description.

If a client has to load a very large catalog of tools, look for features that load definitions on demand. The Claude API, for example, offers a tool search tool with deferred loading for exactly this case.

12. Registry and Governance

How the registry works. The official MCP Registry is a catalog of metadata about publicly accessible servers. It does not host code. Its entries point to packages on npm, PyPI, or Docker Hub, or to remote server URLs. The project describes it as being in preview, so breaking changes and data resets are possible.

Server names follow a reverse DNS format, such as io.github.username/server, and publishers prove they own the matching GitHub account or domain. That stops someone from claiming another project’s name inside the registry. It does not scan code, though. The registry delegates security scanning to package registries and to the marketplaces that consume its data. A listing is a pointer, not an endorsement.

How the governance works today. On December 9, 2025, Anthropic announced it was donating MCP to the Agentic AI Foundation, a directed fund under the Linux Foundation. Anthropic, Block, and OpenAI co-founded the foundation. Anthropic said that technical decisions would stay with the maintainers who already steward the protocol, guided by community proposals. For you as a builder, that means the protocol is no longer one company’s product, and changes arrive through a public proposal process.

13. Common Mistakes

  • Printing to stdout in a stdio server: It breaks the protocol stream. Send your logs to stderr instead.
  • Following old tutorials: Many still describe initialize, sessions, and the HTTP+SSE transport. Check which spec version a tutorial targets.
  • Raising a generic exception for tool errors: The model sees a vague message. Use the SDK’s error type, or return isError: true with a clear message.
  • Installing servers by name alone: Copycat packages exist. Always confirm who published the package.
  • Committing tokens in .mcp.json: Use ${VAR} references and keep the values in your environment.
  • Giving broad credentials for convenience: A token that can read everything will eventually be used to read everything.
  • Skipping human approval for write actions: Approval prompts are annoying until the first bad tool call.
  • Exposing a local HTTP server without authentication: Other processes on the machine can reach it. Prefer stdio for local use, or require a token.
  • Building a proxy that passes client tokens downstream: The specification forbids it.

14. Frequently Asked Questions

What is an MCP server?

An MCP server is a program that exposes tools, resources, or prompts through the Model Context Protocol. A client, such as an AI coding assistant, connects to it, lists what it offers, and calls those capabilities when needed.

Is MCP the same as function calling?

No, they are different things. Function calling is a feature of a model API, where you describe tools in the request and handle the calls yourself. MCP standardizes how a client discovers and calls tools that live in separate servers. Many clients use MCP to find tools and function calling to present them to the model.

Should I use stdio or HTTP?

Use stdio for local tools that run on the user’s machine. It is simple and keeps the server reachable only by the client that launched it. Use Streamable HTTP when a server is remote, shared, or needs its own authentication.

Do I need OAuth?

A remote server that acts on behalf of users needs real authentication, and the specification uses OAuth for it. A local stdio server usually does not, because it runs under the user’s own account.

Why did old MCP tutorials stop working?

The 2026-07-28 revision removed the initialize handshake and protocol-level sessions, and it changed how servers ask for input. SDK major versions followed. Use a current SDK and a current tutorial. The code in this article matches the 2.x SDKs I tested.

Is it safe to install community MCP servers?

It is as safe as installing any code you did not write, and sometimes less so, because the server can see what the model sees. Check the publisher, read the tool list, restrict credentials, and keep approvals on for risky actions.

Can one model call tools from many servers?

Yes, it can do that. A host can connect to several servers at once. Tool names can collide across servers, so clients usually prefix them with a server identifier.

What replaced MCP sampling and roots?

Both are deprecated and still work during the deprecation window. The changelog suggests passing directories as tool parameters or resource URIs instead of using roots, and calling a model provider directly instead of using sampling.

Where do I find servers?

Start with the official MCP Registry and with the vendor’s own documentation. Treat third-party marketplaces as discovery tools, not as safety checks.

15. Conclusion

MCP solves a real problem. It gives AI tools one shared way to reach your data and actions, and the 2026-07-28 revision made it simpler to run by removing sessions and the handshake. Writing a useful server takes under fifty lines.

The hard part is trust. A server runs with real privileges and feeds text straight into a model. The incidents so far, from a copycat email-stealing package to flaws in the debugging tools, all came from trusting a connection too quickly.

Start with a small local server that you wrote. Add tools one at a time. Keep approvals on for anything that writes. When you share a server, add authentication and least-privilege scopes. Then your assistant gets new abilities without getting new ways to hurt you.

If you want to go deeper, read my guides to Claude Code and AI-powered IDEs. The next articles in this series cover local models and agent frameworks.

16. References

Official specification and documentation:

Governance and foundation news:

Incidents and security advisories:


Back to All Posts
Share this post:
Share on X
Share on LinkedIn
Share on Reddit
Share on Facebook
Copy Link
Copied!