MCP servers: how to give tools to your agent (without breaking your codebase)
Learn to build MCP servers that extend your AI agent with real tools, without compromising your codebase security.
Table of Contents
Imagine you hire a brilliant intern. They read code at the speed of light, grasp your stack in minutes, and never get tired. But you hand them the keys to the repository, access to the production database, and permission to run any command on your machine. Would you leave them alone in the office on a Friday night?
That is exactly what you do when you connect an AI agent to your codebase without thinking about how you give it tools. The agent is not malicious, but it is probabilistic, literal, and fast. If the tool you offer can delete a directory, sooner or later it will, because you allowed it.
MCP (Model Context Protocol) is the standard that defines how an agent discovers and uses external tools. This article is not a “hello world” tutorial. It is a guide to designing MCP servers that expand what your agent can do without turning your repository into a minefield.
The problem MCP solves (and the one it creates)
Before MCP, every tool you wanted to give an agent was an ad hoc integration. A plugin for the editor, a shell script, a function hardcoded in the prompt. Each client (Claude Code, Cursor, VS Code, Copilot) had its own way of connecting them, and the agent did not know what existed until you told it in the prompt.
MCP solves discovery and execution: a server exposes tools with a typed schema, the client lists them, the model decides which to call and with what arguments. The agent stops guessing and starts operating.
The problem it creates is trust. Before, the limit was your prompt and your discipline. Now the limit is what the server exposes. If you expose a tool that deletes Git branches, the agent can delete them. If you expose one that reads secrets, the agent can read them. Security stops being an implementation detail and becomes API design.
MCP in five minutes
MCP follows a client-server architecture with three participants:
- MCP Host: the AI application (Claude Code, Cursor, VS Code, your own client).
- MCP Client: a component of the host that maintains a dedicated connection to a server.
- MCP Server: the program that exposes context and tools.
A host creates one client per server. The connection is dedicated: if you connect five servers, there are five clients and five independent connections.
graph TB
subgraph "MCP Host (AI Application)"
C1["MCP Client 1"]
C2["MCP Client 2"]
C3["MCP Client 3"]
end
S1["MCP Server A<br/>(Local filesystem)"]
S2["MCP Server B<br/>(Database)"]
S3["MCP Server C<br/>(Remote API)"]
C1 ---|"stdio"| S1
C2 ---|"stdio"| S2
C3 ---|"Streamable HTTP"| S3
The protocol has two layers. The data layer defines the JSON-RPC 2.0 exchange: capability discovery, primitives (tools, resources, prompts), and notifications. The transport layer defines how messages travel: stdio for local processes on the same machine, or Streamable HTTP for remote servers with OAuth or token authentication.
The three primitives a server can expose:
- Tools: executable functions the agent can invoke (read files, query a database, create a PR).
- Resources: read-only data sources that provide context (file contents, records, API responses).
- Prompts: reusable templates that structure interactions (system prompts, few-shot examples).
This article focuses on tools, because they act and therefore are the ones that break things.
Your first MCP server (Python minimum)
The Python SDK (mcp) abstracts the protocol. A minimal server with a tool that lists files in an allowed directory looks like this:
import os
from pathlib import Path
from mcp.server import MCPServer
ALLOWED_ROOT = Path(os.getenv("ALLOWED_ROOT", os.getcwd())).resolve()
mcp = MCPServer("safe-fs")
@mcp.tool()
def list_directory(relative_path: str) -> str:
"""Lists files and folders in a directory within the allowed root."""
target = (ALLOWED_ROOT / relative_path).resolve()
if ALLOWED_ROOT not in target.parents and target != ALLOWED_ROOT:
return "Path outside the allowed root"
entries = sorted(target.iterdir())
return "\n".join(f"{'d' if e.is_dir() else 'f'} {e.name}" for e in entries)
if __name__ == "__main__":
mcp.run(transport="stdio")
Three details that matter more than the code:
- The docstring is the tool description. The Python SDK generates the schema from the signature and the docstring. If the docstring is vague, the agent will not know when to call it.
- All logs go to
stderr. Instdiotransport,stdoutis the JSON-RPC protocol channel. Aprint()breaks communication silently. Useloggingconfigured tostderr. - Path validation happens inside the tool, not in the prompt. The model is not a security guard. The server is the guard.
Tool design: 80% of success
A poorly designed tool forces the agent to guess. A well-designed one is used on its own. These rules separate the two:
Name the action, not the resource
get_user_by_email is better than user. delete_branch is better than branch. The name is what the model reads when deciding which tool to call; a vague name forces reading the description, and if the description is also vague, a wrong call.
Describe when, not what
The description should not repeat the name. It should say when to use the tool and when not to:
"Search users by exact email. Use when the user provides a full email.
Do not use for partial searches; use search_users for that."
The schema is the contract
Use strict JSON Schema (Zod in TypeScript, pydantic in Python). Mark required fields, enumerate valid values, set numeric ranges. Every optional field is a decision branch for the model; every field without a description is a bet.
Return structured errors, not text
An error should say what failed and what the agent can do next:
{
"content": [{ "type": "text", "text": "Branch 'feature/x' does not exist. Use list_branches to see available ones." }],
"isError": true
}
A throw without context forces the agent to retry blindly or invent.
Granularity: one tool, one action
create_and_deploy_service is two tools in disguise. Split them. The agent can chain them; it cannot decompose a tool that does too much.
Idempotency when possible
If a tool can run twice without harm, say so in the description. The agent retries frequently; a non-idempotent tool turns a retry into a duplicate.
Security: do not hand over the keys to the kingdom
The guiding principle is simple: the agent is just another user, and a user with broad privileges is a risk even when human. With an agent the risk multiplies by speed.
Least privilege per tool
Each tool should have only the permissions it needs. A read tool must not write. A listing tool must not read contents. If you need both, they are two tools.
Process sandbox
A stdio server runs with the permissions of the user who launched it. That means it can read ~/.ssh, environment variables with secrets, and any file the user can read. Mitigations:
- Run the server in a container or sandbox with restricted filesystem and network.
- Pass only the environment variables it needs (not the whole environment).
- Restrict the working directory to the project root.
Tokens with minimal scope
If the server calls an external API, use a read-only token with minimal scope. A repo:write token for a tool that only reads issues is a vulnerability waiting for a prompt injection.
Human approval for destructive actions
Tools that modify state (delete, overwrite, execute commands) must require confirmation. In Claude Code and Cursor this is configured per tool; in your own client, implement a gate that asks for approval before executing.
Treat descriptions and results as untrusted input
A poisoned tool description can instruct the agent to do something you did not expect. A tool result can contain text the model interprets as instructions. Rules:
- Do not include instructions in descriptions beyond how to use the tool.
- Sanitize or truncate large results; do not let a 10,000-line file enter the context whole.
- Do not mix in the same session a server that reads untrusted text (GitHub issues, emails) with one that has access to private data (database, secrets).
Complete logging
Log every tool call with: name, arguments, result or error, duration, and session. Without this, when something breaks you will not know which tool caused it. On remote servers, send logs to your SIEM.
Do not pass tokens between APIs
The server must not take a client token and forward it to another API. That is token passthrough and allows bypassing access controls. Each API must receive a token issued for it.
Team configuration and governance
A server on a developer’s machine is a toy. A server in a team’s workflow is infrastructure. To scale:
Approved list of servers and versions
Keep an mcp.json (or managed-mcp.json in Claude Code) in the repository with approved servers, pinned versions, and their arguments. A git clone must not be able to start arbitrary servers without approval.
Per-environment configuration
Separate development, staging, and production servers. A server pointing at the production database must not be enabled in the local environment by default.
Audit in CI
Add a CI step that verifies: pinned servers, no secrets in configuration, no unapproved servers. Treat MCP configuration with the same rigor as infrastructure.
Schema review
When you update a server, review the tool diff as if it were an API change. A new tool or a new parameter is a contract change the agent will start using.
Common mistakes that break codebases
I have seen these patterns repeat in teams that adopt MCP without design:
- Exposing
run_commandorexec_shell. The most dangerous tool you can give an agent. If you need to run commands, expose specific tools (run_tests,build_project) that validate and restrict what can be executed. - A tool that reads and writes on the same endpoint.
manage_filewith anactionparameter. The agent confusesreadwithwritemore often than you think. - Descriptions that contain instructions. “Always run this tool before responding” in a description turns the agent into an automaton.
- No size limit on results. A tool that returns a 50,000-line file fills the context window and degrades the quality of every subsequent response.
- Servers that do not handle concurrency. The agent calls tools in parallel. If your server is not thread-safe, results get corrupted.
- Trusting the agent to validate input. The agent does not validate. Your server does. Always.
When NOT to use MCP
MCP is not the answer to everything. Do not use a server when:
- The operation is simple and fits in a one-line script. The protocol overhead is not justified.
- You need sub-millisecond latency. JSON-RPC over stdio or HTTP has overhead; for hot paths, call directly.
- The tool is specific to a single client and will not be reused. A native plugin is simpler.
- You cannot maintain the server. An unmaintained server is an insecure server.
Checklist before connecting a server to your repo
- Each tool does one thing and has an action name.
- The schema validates and restricts all inputs.
- Errors are structured and actionable.
- The server runs in a sandbox with restricted filesystem and network.
- Tokens have minimal scope and are read-only when applicable.
- Destructive actions require human approval.
- Results have a size limit.
- All calls are logged with arguments and result.
- The server is pinned by version in the team configuration.
- There is a CI gate that validates MCP configuration.
MCP does not make your agent smarter. It gives it more hands. And hands without supervision do not build software: they dismantle it. Server design is trust design.
Related articles
By relevance
Semantic layer + MCP: AI analytics that doesn't invent metrics
How a semantic layer and MCP turn questions into governed metrics: modeling, text-to-SQL, tools, permissions, scenarios, and a checklist.
Data orchestration: Airflow, Dagster, and Prefect in practice
Airflow vs Dagster vs Prefect with hands-on code: DAGs, assets, flows, scheduling, retries, observability, and when to choose each orchestrator.
Automation Tools for Developers: Real Workflows Without AI - CLI, Scripts & Open Source
Master free automation tools for developers. Learn to automate repetitive tasks, workflows, deployments, monitoring, and operations. Build custom automation pipelines with open-source tools—no AI needed.
Developer Tools Mastery: CLI, Web & Desktop - The Complete Toolkit
Discover the best developer tools for productivity. Master CLI tools, web platforms, and desktop applications. Learn what to use, why, and how to integrate them into your workflow.