Courses / Agentic AI from Scratch (Python)
Session 30 of 40
MCP in a company: tool discovery, authorization, secure connections and governance
Notes
How to Secure an MCP Server in a Company: Tool Discovery, Authorization, Secure Connections and Governance
Agentic AI Foundations · Session 30
Before you start: what do I need before I secure an MCP server?
You need the code folder for this session open in your terminal. It holds session 29’s server, code/ticket_server.py, now with a lock in it, and three new files: code/governance.py (the approved list), code/list_tools.py (a client that lists the tools) and code/refuse_demo.py (a read-only caller that is refused). code/call_server.py is session 29’s client, now starting the server through code/governance.py. Install the libraries with pip install mcp langchain langchain-openai langchain-chroma langchain-community langchain-text-splitters langgraph langgraph-checkpoint-sqlite, then build the ticket database with python code/build_index.py and python code/make_tickets_db.py. The listing and refusal demos need no key and no paid service, and no real credentials are needed: the lab passes a caller name and a list of permissions through the environment. Only code/ask_copilot.py calls a model. Have paper or a notes app ready for the flashcards and the model answer.
Summary: what does it take to make a shared MCP server safe inside a company?
A server that several assistants share has to answer three questions. What does it offer, who is calling, and what did it do? A client finds out what a server offers by asking for its tool list. The server decides what each caller may do, in its own tool code, and refuses the rest with a message the model can read. The company decides which servers an assistant may start, and keeps a record of each call. This session builds those three on the session 29 ticket server: a permission check, an approved-server list and an audit file. The permission check is coarse and tied to how the server is launched; session 35 adds a finer rule about which tickets each person may see.
Key concepts: what do the MCP security terms mean?
| Term | Definition |
|---|---|
| Tool discovery | A client asking a server for its tools and getting each one’s name, description and input schema. |
| Input schema | The description of the arguments a tool accepts, which the model reads to build a call. |
| Authentication | Working out who the caller is. |
| Authorization | The server deciding what an identified caller may do. |
| Permission | A named right, such as tickets:read or tickets:write, that a caller holds or does not. |
| Bearer token | A string a client sends with each HTTP request to prove it was granted access. |
| OAuth 2.1 | The authorization framework MCP uses for servers reached over HTTP. |
| Least privilege | Giving a caller the smallest set of permissions its job needs. |
| Approved list (allowlist) | The servers a company allows its assistants to start. |
| Audit log | A file with one line per call: who, which tool, allowed or refused, and when. |
ToolError |
The SDK exception a tool raises so the model sees a readable message. |
Explanations: how does MCP tool discovery, authorization and governance work?
How does an MCP client discover the tools a server offers?
Think of a restaurant menu. Before ordering you read what is on offer, and each dish has a name and a description. A shop catalogue adds the details you must give to order an item. In MCP the client sends a tools/list request and the server answers with its tools. Each tool definition carries a name, a description and an input schema, which is a JSON Schema for the arguments. In the Python client this is listing = await client.list_tools(), and the tools are in listing.tools. code/list_tools.py does exactly that, starts the server as a read-only caller, and prints each tool’s name, the first line of its description and the inputs it expects. Run python code/list_tools.py and read what the model would read.
The model reads those descriptions to decide what to call, so they are words the model trusts. The specification tells clients to treat tool annotations as untrusted unless they come from trusted servers. Tool names are unique within one server, and a client that gathers tools from several servers can meet two tools with the same name. The specification suggests prefixing names with a server identifier to tell them apart.
A server can also vary its list by caller. The specification allows the set of tools to depend on the authorization presented on a request, for example returning the tools that the caller’s granted scopes allow. The lab keeps the list fixed and refuses at call time, which is simpler to read.
How does an MCP server refuse a caller who lacks permission?
Picture a hotel key card. It identifies you, and it opens your room and the gym but not the other rooms. Authentication is the part that works out who you are; authorization is the part that decides what the card opens. For the Copilot, the IT team’s assistant is known as a reader. Its lookup_ticket call is allowed. Its create_ticket call is not.
Now the failure first. A hostile message in a ticket talks the IT assistant’s model into creating a ticket, and a ticket appears. The assistant’s prompt said “do not create tickets”, but a prompt is a polite sign on a door and the model chooses which tool to call. The server checked nothing, so nothing stopped the call. The fix is a lock in the server’s tool code, where a fooled model still meets it.
CALLER_ID = os.environ.get("CALLER_ID", "unknown")
PERMISSIONS = {p.strip() for p in
os.environ.get("CALLER_PERMISSIONS", "").split(",") if p.strip()}
def require(permission, tool, detail):
if permission not in PERMISSIONS:
audit(tool, "refused", f"needs {permission}")
raise ToolError(f"This caller may not use {tool}: "
f"it needs the {permission} permission.")
audit(tool, "allowed", detail)
@mcp.tool()
def create_ticket(title: str) -> str:
"""Raise a new help desk ticket. Needs the tickets:write permission."""
require("tickets:write", "create_ticket", title)
...
This is code/ticket_server.py, shortened: lookup_ticket calls require("tickets:read", ...) in the same way, and the resource does too.
ToolError comes from mcp.server.mcpserver.exceptions. When a tool raises it, the model sees the message and can recover. A tool that raises an ordinary exception is treated as a crash: the model learns just that the call failed.
The lab gives each caller the smallest set of permissions its job needs, which is the idea of least privilege. In code/governance.py the two sets are READ_ONLY (tickets:read) and READ_WRITE (tickets:read,tickets:write). The IT assistant holds READ_ONLY. The Copilot’s own calls through call_ticket_tool in code/call_server.py hold READ_WRITE, and a person’s yes in the graph still comes before any write.
Now see the refusal. Run python code/refuse_demo.py. The caller it-assistant holds only tickets:read. Look for three things: the lookup comes back with ticket text, the create_ticket call comes back as a refusal that names the missing permission, and the audit.log the script prints has one line for each call. To see a different caller, change PERMISSIONS in code/refuse_demo.py (the line marked CHANGE ME) to READ_WRITE and run it again; the ticket is then really created, so run python code/make_tickets_db.py afterwards to reset the table.
How is the connection secured: stdio compared with HTTP?
The two standard connection types carry identity differently. The specification says authorization is optional for MCP implementations. A server reached over HTTP should follow the authorization specification, which is based on OAuth 2.1. A server on stdio should not follow it and instead retrieves credentials from the environment.
| Connection | Where the caller’s identity comes from | Who checks it |
|---|---|---|
| stdio | The environment of the process that launched the server | The server’s own tool code; the security boundary is the launching process |
| Streamable HTTP | A bearer token sent with each request | The server, which treats itself as an OAuth resource server and validates the token |
Over HTTP the details matter. The server should answer a missing, invalid or expired token with HTTP 401, and a token with too few permissions with 403. It should check that a token was issued for it as the intended audience. It should not accept tokens issued for other services, and it should not pass a token it received on to another service. The specification calls token passthrough an anti-pattern and forbids it, because downstream logs can show a different caller than the real one, and a token accepted by several services can be reused across them. The Python SDK describes an HTTP server as an ordinary web service protected with OAuth 2.1 bearer tokens; a TokenVerifier you supply looks at each request’s token.
Over stdio the SDK is blunt: on stdio the security boundary is the process that started the server, and the token check is not consulted there. That is why the lab’s caller identity is as trustworthy as the launcher that sets it, and no more. It teaches where the check belongs. It is not a substitute for real sign-in on a shared service.
What are MCP governance controls: an approved list and an audit log?
An approved-supplier list says a buyer may order from vetted companies. A visitor log at reception says who came in, whom they saw and when. MCP governance has the same two parts. The list says which servers an assistant may start. The log shows what the servers did.
ALLOWED_SERVERS = {"tickets": [str(HERE / "ticket_server.py")]}
APPROVED_TOOLS = {"lookup_ticket", "create_ticket"}
def server_params(name, caller_id, permissions):
if name not in ALLOWED_SERVERS:
raise PermissionError(f"Server {name!r} is not on the approved list.")
return StdioServerParameters(
command=sys.executable, args=ALLOWED_SERVERS[name],
env={"TICKETS_DB": str(TICKETS_DB), "AUDIT_LOG": str(AUDIT_LOG),
"CALLER_ID": caller_id, "CALLER_PERMISSIONS": permissions},
)
This is code/governance.py. It also holds check_tool_approved(), which code/call_server.py runs before it calls a tool: a tool that is not on APPROVED_TOOLS is refused on the client side, as a second, earlier check. The server’s own require() is the lock that matters.
The approved list matters because a local server is a program that runs with the same privileges as the client. For clients that offer one-click setup of a local server, the specification requires a consent step before any command runs, and says to show the exact command and get explicit approval. For stdio servers meant to run locally, it recommends the stdio transport itself because it limits access to the client that started the server.
The audit line goes to a file. It does not go to standard output, because on stdio the output stream carries the messages. The specification’s own advice for tool servers lines up: validate tool inputs, apply access controls, rate limit calls, and have clients log tool usage for audit purposes. The scope design guidance adds that a progressive least-privilege model keeps a stolen token’s reach small and keeps audit trails clear.
def audit(tool, outcome, detail):
line = {"time": datetime.now(timezone.utc).isoformat(), "caller": CALLER_ID,
"tool": tool, "outcome": outcome, "detail": detail}
with open(AUDIT_LOG, "a") as handle:
handle.write(json.dumps(line) + "\n")
This is audit() in code/ticket_server.py. Each line of audit.log is one JSON object, and require() calls audit() for both outcomes, so the refused call is in the file too. Open audit.log after python code/refuse_demo.py and find the refused line for create_ticket.
What goes wrong when an MCP server has no checks?
Three situations show the gap.
- An assistant with read access creates a ticket after a hostile message. The rule lived in the prompt and the server checked nothing. Fix: a permission check in the tool code.
- A server hands the caller’s token on to another service, and a stolen token reaches data it was not meant for. The server accepted a token that was not issued for it and did not check the audience. Fix: accept tokens issued for this server and no others, and do not forward them.
- An incident review cannot say who created a ticket last Tuesday. The server kept no record. Fix: an audit line for each call, refused ones included.
| What you learned | The design decision | Where it shows |
|---|---|---|
| A model chooses the tool, not the server | Put the permission check in the tool code | require() in code/ticket_server.py |
| Identity differs on stdio and HTTP | Environment on stdio, bearer token on HTTP | server_params() in code/governance.py |
| A local server runs with the client’s privileges | Start approved servers, refuse the rest | ALLOWED_SERVERS in code/governance.py |
| A refusal with no record is hard to investigate | One audit line per call, allowed or refused | audit.log |
Flashcards: how well do I know the MCP security controls?
Say the answer aloud before revealing it. Speaking is a different skill from reading, so practise both.
1. What is tool discovery?
It is the client asking a server what it offers with a tools list request. Each tool comes back with a name, a description and an input schema, like reading a menu before you order.2. Why treat a server's tool descriptions with care?
The model reads them to decide what to call, so they are words the model trusts. The specification tells clients to treat tool annotations as untrusted unless they come from trusted servers.3. What is the difference between authentication and authorization?
Authentication works out who the caller is. Authorization decides what that caller may do. A hotel key card identifies you and then opens some doors and not others.4. Why is "do not create tickets" in a prompt not enough?
A prompt is a polite sign, and the model chooses which tool to call. A hostile message can talk it round. A permission check in the server's tool code is the lock a fooled model still meets.5. How does a tool refuse a call so the model understands why?
It raises `ToolError` with a clear message. The model sees the message and can recover. An ordinary exception counts as a crash and tells the model just that the call failed.6. How does a stdio server learn who is calling?
From the environment of the process that launched it, because a pipe has no Authorization header. The security boundary is the launching process, so the identity is as trustworthy as the launcher, and no more.7. How does an HTTP MCP server check a caller?
It treats itself as an OAuth 2.1 resource server and validates the bearer token on each request, answering 401 for a missing or invalid token and 403 for too few permissions.8. What is token passthrough, and why is it forbidden?
It is a server accepting a token not issued for it and passing it on to another service. Downstream logs can show a different caller than the real one, and a token accepted by several services can be reused across them.9. What are the two parts of MCP governance in this session?
An approved list of servers the client may start, and an audit log with one line per call. The list says what may run, and the log shows what did.10. Why does the audit line go to a file and not to the screen?
On stdio the output stream carries the protocol messages, so a printed line can corrupt them. A file keeps the record safe and out of the way.Model answer: how do I explain MCP security in an interview?
The core question this session answers: “A teammate asks: the server is shared by several assistants. How does it know who may do what, and how would we find out afterwards who did what?”
Four beats a teammate listens for, in this order: list what is offered · identify the caller · refuse in the server · keep a record. Skip any of these four and the answer is incomplete.
- List what is offered: the client asks for the tool list.
- Identify the caller: environment on stdio, bearer token on HTTP.
- Refuse in the server: a permission check in the tool code, with a readable error.
- Keep a record: an audit line per call and an approved list of servers.
The full answer, said aloud:
(List what is offered) “A client asks the server for its tools and reads each name, description and input schema. That is how an assistant knows what it can call.
(Identify the caller) On a local server the launching client passes the caller’s identity and permissions in its environment. On an HTTP server each request carries a bearer token that the server validates, and it accepts tokens issued for itself and rejects the rest.
(Refuse in the server) The tool code checks the permission and raises an error the model can read. The check lives in the server because a prompt is a sign on the door, and a hostile message can talk a model round.
(Keep a record) The server writes one audit line per call, allowed or refused, and the client starts servers from an approved list. Afterwards we can say who called which tool and what happened.“
Missing a beat is a failure state. The follow-up question lands where you went quiet: skip the last beat and you are asked how you would investigate an incident. Practise until the four come out without prompting, then stop talking and let the questions come.
Why this matters: why does MCP security matter at work?
In a conversation with a teammate or manager: a security reviewer’s first question about a shared tool server is who can call what and where that is enforced. “In the server’s tool code, with a record” is the answer they want to hear.
On the job: a platform team that publishes internal tools to several assistants needs an approved list, a permission model and logs before the first rollout. The same four beats apply whether the server is a ticket system or something larger.
In the rest of this course: session 31 uses this server from a supervisor and its sub-agents. Session 35 adds the finer rule about which tickets each role may see, and session 36 builds on the audit file when it turns to governance and an audit trail.
After this unit: what do I do after this lesson, and what comes next?
Assignment. List the server’s tools with python code/list_tools.py, run python code/refuse_demo.py with PERMISSIONS = READ_ONLY and again with READ_WRITE, and find the create_ticket lines in audit.log for both runs. Project step. Add require() and audit() to code/ticket_server.py, write code/governance.py, code/list_tools.py and code/refuse_demo.py beside it (the build prompts are code/prompts/1-write-governance.md, code/prompts/2-write-list-tools.md and code/prompts/3-write-refuse-demo.md), and run python code/ask_copilot.py with a ticket question to check the Copilot still works. The brief for the project work is the project file. Next session: several agents, where a supervisor calls other agents as tools.
Want help building this with someone?
Tell us what you are working on and we will write back about a mentor-led cohort, live sessions or 1:1 training. It is only an enquiry: you choose whether to go further.
Ask about mentor-led trainingTechEazy Consulting training material — not affiliated with or endorsed by OpenAI, Anthropic, LangChain or any other company named in this course.