Prev Next

AI / MCP (Model Context Protocol) server Interview questions

Last updated

1. What is MCP (Model Context Protocol)? 2. What problem does MCP solve? 3. What is an MCP server? 4. What are the main roles in MCP architecture? 5. What are the three core server primitives in MCP? 6. What is an MCP tool? 7. What is an MCP resource? 8. What is an MCP prompt? 9. What is the role of JSON-RPC in MCP? 10. What transports does MCP support? 11. What is the stdio transport in MCP? 12. How do you define an MCP tool in Python? 13. How do you define an MCP tool in TypeScript? 14. How do you test an MCP server with MCP Inspector? 15. How do you connect an MCP server to Claude Desktop? 16. What are the client features in MCP? 17. What is the difference between MCP and a REST API? 18. What is the difference between tools, resources, and prompts? 19. What is the difference between MCP and function calling? 20. How does capability negotiation work in MCP? 21. How does the Streamable HTTP transport work? 22. What is the difference between stdio and Streamable HTTP? 23. Why was the HTTP+SSE transport deprecated? 24. How do tool annotations work in MCP? 25. What is the difference between protocol errors and tool execution errors? 26. How does MCP sampling work? 27. What is elicitation and when should you use it? 28. What are resource templates in MCP? 29. How do list_changed notifications work? 30. Why must a stdio MCP server never write logs to stdout? 31. How does pagination work in MCP list operations? 32. What are structured output and outputSchema in MCP tools? 33. What are roots in MCP and why do they matter? 34. How does MCP authorization work for remote servers? 35. Why does MCP require resource indicators in OAuth tokens? 36. What is token passthrough and why is it forbidden in MCP? 37. What is the confused deputy problem in MCP proxy servers? 38. How can tool poisoning attack an MCP-connected assistant? 39. How do you secure a local MCP server? 40. What changed in the 2026-07-28 MCP specification? 41. How does a stateless MCP protocol help horizontal scaling? 42. What is the Multi Round-Trip Requests (MRTR) pattern? 43. Explain the lifecycle of an MCP connection? 44. Explain the execution flow of a tool call end to end? 45. What are MCP tasks and when should you use them? 46. How can you optimize MCP tool design for LLM context? 47. How do you troubleshoot an MCP server that will not connect? 48. When would you choose MCP over direct API integration? 49. How do MCP clients register with an authorization server? 50. How do you observe and monitor a production MCP server?

1. What is MCP (Model Context Protocol)?

Model Context Protocol (MCP) is an open standard that defines how AI applications connect to external tools, data sources, and workflows. Anthropic introduced it in late 2024, and it is now stewarded as an open, community-governed project.

Think of it as a common plug between an LLM application and the outside world. Instead of every app writing custom glue code for GitHub, Slack, or a database, a service exposes one MCP server and any MCP-capable app can use it.

Under the hood, MCP is a client-server protocol built on JSON-RPC 2.0. A server advertises what it can do (tools, resources, prompts), and the client discovers those capabilities at runtime.

Take quiz
MCP is built on which message format?
GraphQL over WebSocket
gRPC with protobuf
SOAP envelopes
JSON-RPC 2.0
What does MCP standardize?
How models are trained on private data
How AI applications connect to external tools and data
How GPUs are scheduled for inference
How prompts are tokenized

2. What problem does MCP solve?

MCP removes the N x M integration problem. Without a standard, N AI applications each need a custom connector for M tools, which means N x M pieces of glue code to build and maintain.

With MCP, each tool provider writes one server (M) and each AI application implements one client (N). The work drops to roughly N + M.

Without MCP With MCP
Custom connector per app and per tool One server works with every MCP client
Each integration has its own auth and schema style Shared discovery, schemas, and message format
Tool changes break every app Server updates are picked up through discovery

It also gives tool discovery a standard shape, so an assistant can find out what a server offers instead of being hard-coded for it.

Take quiz
MCP reduces integration effort from N x M connectors to roughly:
N + M
N x N
M squared
a single global connector
In an MCP world, who writes the connector for a given SaaS product?
Every AI application writes its own private adapter
The end user writes a plugin per chat window
The provider publishes one MCP server that any client can use
The LLM vendor retrains the model for that API

3. What is an MCP server?

An MCP server is a program that exposes capabilities to AI applications through the Model Context Protocol. It wraps something real, such as a database, a file system, a SaaS API, or a build tool, and presents it in a uniform way.

A server can offer three kinds of features: tools (actions), resources (readable data), and prompts (reusable templates). It answers requests like tools/list and tools/call from a client.

Servers run in two common ways: as a local process launched by the host over stdio, or as a remote service reachable over Streamable HTTP.

Take quiz
Which request does a client send to ask a server what tools it offers?
tools/describe
tools/list
server/getTools
capabilities/tools
An MCP server that runs as a local child process usually talks over:
a raw UDP socket
SMTP
a shared database table
stdio

4. What are the main roles in MCP architecture?

MCP defines three roles: the host, the client, and the server.

The host is the AI application the user interacts with, for example Claude Desktop or an IDE. Inside the host, one MCP client object is created per server connection. Each client keeps a 1:1 link with a single server, which supplies the tools and data.

flowchart LR
  U[User] --> H["Host application"]
  H --> C1["MCP client A"]
  H --> C2["MCP client B"]
  C1 <--> S1["MCP server: files"]
  C2 <--> S2["MCP server: database"]

This split keeps servers isolated from each other. A files server never sees what a database server returns unless the host decides to put both in the model's context.

Take quiz
How many servers does a single MCP client instance connect to?
All servers configured in the host
Up to ten, round-robin
Exactly one
None, it talks to the model only
Which component owns the user interface and decides what goes into the model's context?
The host
The server
The transport layer
The JSON-RPC library

5. What are the three core server primitives in MCP?

Servers expose tools, resources, and prompts. What separates them is who decides to use them.

Primitive Purpose Controlled by Key methods
Tools Executable actions with side effects or computation Model tools/list, tools/call
Resources Read-only context such as files or records Application resources/list, resources/read
Prompts Reusable message templates User prompts/list, prompts/get

Many servers only ship tools, but using all three lets you separate actions, background data, and user-triggered workflows cleanly.

In practice, clients decide how each one surfaces: tools go to the model, resources appear in an attachment picker, and prompts show up as commands.

Take quiz
Which primitive is typically invoked by the model on its own?
Prompts
Roots
Resources
Tools
Which primitive is meant to be picked by the user, like a slash command?
Tools
Prompts
Sampling
Resource templates

6. What is an MCP tool?

A tool is a function a server exposes so the model can take an action or run a computation, such as create_issue or run_query.

Each tool has a unique name, a human-readable description, and an inputSchema written in JSON Schema. The model reads these to decide when and how to call it. Newer revisions also allow an outputSchema and annotations.

A call looks like this:

{ "jsonrpc": "2.0", "id": 7, "method": "tools/call",
  "params": { "name": "get_weather",
              "arguments": { "city": "Charlotte" } } }

The result comes back as a list of content blocks (text, images, embedded resources) plus an optional isError flag.

Take quiz
Which field tells the model what arguments a tool accepts?
inputSchema
returnType
argsManifest
toolSignature
A tool result is returned as:
A raw SQL cursor
A binary stream with no structure
A list of content blocks
A single integer status code

7. What is an MCP resource?

A resource is data a server makes available for reading, identified by a URI such as file:///logs/app.log or postgres://db/customers.

Clients discover resources with resources/list and fetch their contents with resources/read. Content can be text or base64 binary, and each resource carries a MIME type.

Resources are typically application-controlled: the host decides which ones to attach to the conversation, often after the user picks them. They give the model context without performing an action.

Typical prompt examples include a bug-report template, a code-review checklist, or a meeting-summary format that the user fills in with a few arguments.

Take quiz
How is an MCP resource identified?
By a numeric port
By a URI
By a JWT subject
By the tool name
Which method fetches the contents of a resource?
resources/execute
resources/download
resources/open
resources/read

8. What is an MCP prompt?

An MCP prompt is a reusable, parameterized message template that a server offers to the user. A code-review server might expose a review_pull_request prompt that takes a PR number and expands into a well-written set of messages.

Clients list them with prompts/list and expand one with prompts/get, passing arguments. The server returns ready-to-use messages, which can include embedded resources.

Prompts are user-controlled. They typically appear as slash commands or menu entries rather than being called by the model.

Take quiz
Which method expands a prompt with arguments into messages?
prompts/run
prompts/render
prompts/get
prompts/call
Who normally chooses to use an MCP prompt?
The user
The transport layer
The authorization server
The network load balancer

9. What is the role of JSON-RPC in MCP?

MCP uses JSON-RPC 2.0 as its wire format. Every message is one of three shapes: a request (has id and method), a response (has the same id plus result or error), or a notification (a method with no id, so no reply).

// request
{"jsonrpc":"2.0","id":1,"method":"tools/list"}
// notification (no id, no response expected)
{"jsonrpc":"2.0","method":"notifications/tools/list_changed"}

Because it is transport-agnostic, the same messages travel over stdio or HTTP without changes.

Requests and responses are matched by id, which lets several calls be in flight at once without mixing up their results.

Take quiz
A JSON-RPC message that has no id field is a:
Batch request
Error response
Handshake
Notification
JSON-RPC lets MCP use the same messages over:
Only TCP port 8080
Any supported transport
Only WebSockets
Only local pipes

10. What transports does MCP support?

The specification defines two standard transports: stdio and Streamable HTTP.

stdio Streamable HTTP
Host launches the server as a child process Server runs independently as an HTTP service
Messages over stdin and stdout Single HTTP endpoint using POST, with optional SSE streaming
Best for local tools and single-user setups Best for remote, multi-client, hosted servers
Trust comes from the local OS user Needs real authentication such as OAuth

The older HTTP+SSE transport (two endpoints) is deprecated and replaced by Streamable HTTP. Custom transports are allowed as long as they preserve the JSON-RPC message format.

Take quiz
Which pair are the standard MCP transports?
stdio and Streamable HTTP
WebSocket and gRPC
SMTP and IMAP
MQTT and AMQP
The deprecated transport that Streamable HTTP replaced is:
Long polling over FTP
Raw TCP framing
HTTP+SSE with two endpoints
Named pipes on Windows only

11. What is the stdio transport in MCP?

With stdio, the host starts the MCP server as a subprocess and exchanges JSON-RPC messages through its standard streams. The client writes to the server's stdin and reads from its stdout.

Messages are newline-delimited, so a single message must not contain embedded newlines. The server may write logs to stderr, and the client can capture or ignore them.

It is the simplest option: no ports, no networking, and the server inherits the user's local permissions. That also means a stdio server can do whatever the user account can, so only run ones you trust.

Take quiz
In stdio transport, where should a server write diagnostic logs?
stdout
stderr
The MCP initialize response
A separate TCP socket
How are JSON-RPC messages separated in stdio?
By null bytes
By HTTP chunk headers
By length-prefixed binary frames
By newlines

12. How do you define an MCP tool in Python?

The official Python SDK ships FastMCP, which turns a typed function into a tool. The name comes from the function, the description from the docstring, and the input schema from the type hints.

from mcp.server.fastmcp import FastMCP

mcp = FastMCP("calculator")

@mcp.tool()
def add(a: int, b: int) -> int:
    """Add two integers and return the sum."""
    return a + b

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

Write the docstring for the model, not for yourself. It is what the LLM reads to decide when to call the tool.

Take quiz
In FastMCP, where does a tool's description come from?
A separate YAML file
The module filename
The function docstring
The return type annotation
Which decorator registers a function as a tool in FastMCP?
@mcp.tool()
@mcp.route()
@mcp.resource_only
@server.endpoint()

13. How do you define an MCP tool in TypeScript?

With the TypeScript SDK you create an McpServer, register tools with a Zod schema for the inputs, and connect a transport.

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: "calculator", version: "1.0.0" });

server.registerTool(
  "add",
  { description: "Add two numbers", inputSchema: { a: z.number(), b: z.number() } },
  async ({ a, b }) => ({ content: [{ type: "text", text: String(a + b) }] })
);

await server.connect(new StdioServerTransport());

Zod gives you runtime validation and the JSON Schema the client sees, from one definition.

Take quiz
Which library does the TypeScript SDK commonly use to describe tool inputs?
Mongoose
Sequelize
Handlebars
Zod
What does a TypeScript tool handler return so the client can read it?
A bare string only
An object with a content array
A Promise with no value
An HTTP Response object

14. How do you test an MCP server with MCP Inspector?

MCP Inspector is the official visual testing tool. It connects to your server as a client, so you can list and call tools, read resources, and expand prompts without wiring up a full AI app.

Start it with npx and pass the command that launches your server:

npx @modelcontextprotocol/inspector python server.py

It opens a local web UI. From there:

  1. Check the connection and negotiated capabilities.
  2. Open the Tools tab, pick a tool, fill in arguments, and run it.
  3. Inspect the raw JSON-RPC traffic and server logs when something fails.
Take quiz
What is the quickest way to launch MCP Inspector against a Python server?
npx @modelcontextprotocol/inspector python server.py
pip install inspector-mcp --run
docker run mcp-test server.py
python -m mcp.inspect --mode=prod
Why test with Inspector before connecting to an AI host?
It trains the model on your tools
It deploys the server to production
You can call tools directly and see raw JSON-RPC messages
It encrypts tool arguments automatically

15. How do you connect an MCP server to Claude Desktop?

Claude Desktop reads a JSON config file and launches each listed server as a subprocess. Add your server under the mcpServers key, then restart the app.

{
  "mcpServers": {
    "calculator": {
      "command": "python",
      "args": ["/absolute/path/to/server.py"],
      "env": { "API_KEY": "your-key-here" }
    }
  }
}

Use absolute paths. GUI apps often do not inherit your shell's PATH, so a bare node or uv can fail to resolve. For remote servers, newer builds let you add them as connectors by URL instead of editing this file.

Take quiz
Which top-level key holds server definitions in the Claude Desktop config?
servers
mcpServers
toolProviders
pluginRegistry
Why are absolute paths recommended in the config?
JSON does not allow relative paths
Relative paths are blocked for security by the spec
It makes the server run faster
GUI apps may not share your shell PATH or working directory

16. What are the client features in MCP?

Besides consuming server features, clients can offer capabilities the server can ask for. The three main ones are:

Feature What it lets the server do
Sampling Ask the client to run an LLM completion on its behalf
Roots Learn which directories or URIs it is allowed to work in
Elicitation Ask the user for extra input mid-task

These are declared during capability negotiation, so a server only uses what the client advertised. Because each one routes through the client, the host stays in control of model access, scope, and user consent.

Take quiz
Which client feature lets a server request an LLM completion?
Roots
Pagination
Sampling
Annotations
Which client feature tells a server which directories it may operate in?
Roots
Elicitation
Prompts
Completion

17. What is the difference between MCP and a REST API?

A REST API is designed for developers who read the docs and write code against fixed endpoints. MCP is designed for AI clients that discover capabilities at runtime and decide what to call.

REST API MCP server
Endpoints documented separately (OpenAPI, docs) Self-describing: tools/list returns names, descriptions, schemas
Client code is written per API One generic client works with any server
Mostly request-response from client to server Two-way: servers can request sampling or user input
Auth and conventions vary by API Standard capability negotiation and an OAuth-based auth model

They are not rivals. Many MCP servers simply wrap an existing REST API and translate it into tools the model can understand.

Take quiz
What makes MCP different from a plain REST API for AI use?
It only works with GraphQL back ends
It removes the need for authentication
It stores model weights on the server
It is self-describing, so clients discover tools at runtime
Which relationship between MCP and REST is common?
MCP replaces HTTP entirely
An MCP server wraps a REST API as tools
REST must be disabled before MCP works
MCP can only call SOAP services

18. What is the difference between tools, resources, and prompts?

All three are server features, but they differ in intent and who is in control.

A tool does something: it runs code, writes data, or calls an API, and the model chooses when to call it. A resource is passive data the application attaches as context. A prompt is a template the user triggers explicitly.

A rule of thumb for design: if it changes state or computes something, make it a tool. If it is just data to read, make it a resource. If it is a canned workflow the user kicks off, make it a prompt. Some clients only support tools, so important read access is often exposed as a tool too.

Take quiz
You want a read-only schema document attached as context by the app. Best fit?
Resource
Tool
Prompt
Sampling request
An operation that creates a Jira ticket should be a:
Resource
Root
Tool
Prompt argument

19. What is the difference between MCP and function calling?

Function calling is a model API feature: you describe functions in the request, and the model replies with a structured call that your code executes. It says nothing about where those functions live or how they are discovered.

MCP standardizes the other side: how tools are hosted, discovered, authorized, and invoked across applications. A host connects to MCP servers, converts their tool definitions into the model's function-calling format, and routes the model's calls back to the right server.

So they are complementary layers. Function calling is how the model asks for an action; MCP is how the action gets found and executed in a reusable way.

Take quiz
How do MCP and function calling usually work together?
MCP replaces the model's tool-call output format
The host converts MCP tools into function-calling definitions for the model
Function calling is used only between MCP servers
MCP runs the model instead of the host
Function calling alone does NOT define:
That the model can emit structured calls
That arguments follow a JSON schema
That results can be sent back to the model
How tools are discovered and hosted across apps

20. How does capability negotiation work in MCP?

In the 2025-11-25 revision, negotiation happens in the opening initialize exchange. The client sends its protocolVersion, its capabilities, and clientInfo. The server replies with the version it will use, its own capabilities, and serverInfo.

// server capabilities in the initialize result
{ "capabilities": {
    "tools":     { "listChanged": true },
    "resources": { "subscribe": true, "listChanged": true },
    "prompts":   {} } }

Afterward, each side may only use features the other declared. If the client does not advertise sampling, the server must not send a sampling request.

In the 2026-07-28 revision this is reshaped: version and client capabilities travel in _meta on every request, and servers describe themselves through server/discover.

Take quiz
In the 2025-11-25 flow, which message opens the connection and exchanges capabilities?
server/discover
handshake/hello
initialize
capabilities/exchange
If a client does not advertise sampling, a server should:
Not send sampling requests
Send them anyway and wait
Fall back to calling the tool itself
Close the transport immediately

21. How does the Streamable HTTP transport work?

The server exposes a single HTTP endpoint, for example /mcp. The client sends every JSON-RPC message as an HTTP POST to it.

For each POST, the server can answer in one of two ways: a plain application/json response for quick calls, or a text/event-stream (SSE) stream when it needs to send progress, notifications, or server-initiated requests before the final result.

sequenceDiagram
  participant C as Client
  participant S as Server /mcp
  C->>S: POST tools/call
  alt quick result
    S-->>C: 200 application/json
  else long running
    S-->>C: 200 text/event-stream
    S-->>C: progress notifications
    S-->>C: final response
  end

The client must send an Accept header covering both types, and servers must validate the Origin header to block DNS-rebinding attacks.

Take quiz
How does a client send messages over Streamable HTTP?
A new WebSocket per tool
SMTP messages to the server
HTTP PUT to one URL per tool
HTTP POST to a single endpoint
A server needs to stream progress before the final result. It responds with:
application/pdf
text/event-stream
multipart/form-data
text/csv

22. What is the difference between stdio and Streamable HTTP?

The real difference is deployment and trust. Stdio ties the server's lifetime to one client process, while Streamable HTTP lets one server serve many clients over a network.

Aspect stdio Streamable HTTP
Lifecycle Started and stopped by the host Runs on its own, managed like any service
Clients One Many concurrent
Auth Implicit, local user OAuth-based, bearer tokens
Scaling Not applicable Behind load balancers
Typical use Local files, CLI wrappers SaaS integrations, shared team servers

Pick stdio for local developer tooling. Pick Streamable HTTP when the server is shared, hosted, or needs per-user authorization.

Take quiz
Which transport suits a hosted server used by many users?
Streamable HTTP
stdio
Named pipes
Unix signal handlers
Where does authentication usually matter most?
stdio, since it is encrypted by default
Neither, MCP forbids auth
Streamable HTTP, since it is network reachable
Only for resources, never tools

23. Why was the HTTP+SSE transport deprecated?

The original remote transport used two endpoints: a long-lived SSE connection for server-to-client messages and a separate POST endpoint for client-to-server messages. That caused real operational pain.

  • A permanent SSE connection per client is hard to scale and easy to drop behind proxies.
  • Reconnection and resumption were awkward because state lived across two channels.
  • Servers that only needed simple request-response still had to hold a stream open.

Streamable HTTP, introduced in the 2025-03-26 revision, collapses this into one endpoint where SSE is used only when needed per request. The 2026-07-28 revision formally reclassifies HTTP+SSE as deprecated, so new servers should not adopt it.

Take quiz
What did Streamable HTTP simplify compared with HTTP+SSE?
It requires WebSockets
It uses one endpoint, with SSE only when needed
It removes JSON-RPC
It forces every call to stream
What was a pain point of the old HTTP+SSE design?
It could not carry JSON
It only worked on port 25
It required a GPU on the client
A permanent SSE connection per client plus a separate POST endpoint

24. How do tool annotations work in MCP?

Tool annotations are optional hints that describe a tool's behavior so a client can decide how to present or approve it. The standard ones are:

Annotation Meaning
readOnlyHint Tool does not modify its environment
destructiveHint May delete or overwrite data (default is true when not read-only)
idempotentHint Repeating the call with the same arguments has no extra effect
openWorldHint Interacts with external systems outside the server (default true)

A client might auto-approve a readOnlyHint tool but prompt the user before a destructive one.

The key caveat: annotations are hints, not guarantees. A client must not trust them from an untrusted server, because a malicious one could mislabel a dangerous tool as read-only.

Take quiz
Which annotation signals that a tool does not change anything?
safeMode
idempotentOnly
readOnlyHint
noWriteFlag
Why shouldn't clients blindly trust annotations from unknown servers?
They are hints that a malicious server could misstate
They are encrypted and unreadable
They are removed during initialize
They only apply to resources

25. What is the difference between protocol errors and tool execution errors?

MCP separates protocol-level failures from tool-level failures, and the split matters for how the model reacts.

A protocol error is a standard JSON-RPC error: unknown tool name, malformed request, or invalid params (code -32602). It signals that the request itself was wrong.

A tool execution error is a normal result with isError: true and a message in the content. Use it when the tool ran but failed, for example an API timeout or invalid input data.

{ "result": { "isError": true,
    "content": [{ "type": "text",
      "text": "Date must be in the future. Got 2020-01-01." }] } }

The model sees tool execution errors, so it can read the message and retry with corrected input. Since the 2025-11-25 revision, input validation failures should be returned this way to enable self-correction.

Take quiz
A tool ran but the upstream API timed out. How should it report this?
A JSON-RPC method-not-found error
Closing the transport
Returning an empty content array silently
A result with isError: true and a clear message
Why return validation failures as tool execution errors?
Protocol errors are not allowed in MCP
The model can read them and retry with fixed input
It is faster over stdio
It avoids needing a schema

26. How does MCP sampling work?

Sampling lets a server ask the client to run an LLM completion, so the server can use intelligence without holding its own model API key.

The flow: the server sends sampling/createMessage with messages, optional model preferences, and a system prompt. The client may show the request to the user, picks a model, runs it, and returns the completion.

sequenceDiagram
  participant S as Server
  participant C as Client
  participant U as User
  S->>C: sampling/createMessage
  C->>U: review request
  U-->>C: approve
  C->>C: call LLM
  C-->>S: completion

The client stays in control: it can modify, reject, or require human approval. The 2025-11-25 revision also allows tools to be passed within sampling requests for agentic server loops.

Take quiz
Who actually runs the model in an MCP sampling request?
The client
The server
The transport layer
The registry
What is a main benefit of sampling for server authors?
It lets servers bypass user consent
It speeds up stdio startup
No need to manage a model API key on the server
It replaces tool definitions

27. What is elicitation and when should you use it?

Elicitation lets a server pause a task and ask the user for more information through the client, using elicitation/create.

There are two modes:

Mode Use for
Form Simple structured input such as a choice, a date, or a confirmation, described with a limited JSON Schema
URL Sensitive interactions like OAuth consent or entering credentials, handled out-of-band in the browser

Use form mode to clarify a missing argument or confirm a risky action. Use URL mode when the data must not pass through the MCP client or the model, such as a third-party login.

Never request passwords or API keys through form mode.

Take quiz
Which elicitation mode suits a third-party OAuth login?
Form mode
URL mode
Sampling mode
Batch mode
A server needs the user to confirm deleting a project. Best approach?
Guess yes and continue
Open a new stdio stream
Use a prompt template
Form-mode elicitation with a confirm field

28. What are resource templates in MCP?

A resource template describes a family of resources using a URI template (RFC 6570), so the server does not have to list every item individually.

{ "uriTemplate": "file:///logs/{date}.log",
  "name": "Daily log",
  "mimeType": "text/plain" }

A client lists them with resources/templates/list, fills in the variables, and calls resources/read on the resulting URI, such as file:///logs/2026-11-07.log.

They are ideal for large or dynamic sets: per-user records, per-date files, per-ticket pages. Servers can also support argument completion so clients can suggest valid values for each variable.

Take quiz
Which method lists available resource templates?
resources/patterns
templates/get
resources/templates/list
resources/expand
Resource templates are best when:
There are many items identified by a pattern
You have exactly one static file
You need to run a computation
You need to elicit user input

29. How do list_changed notifications work?

When a server's set of tools, resources, or prompts changes at runtime, it can tell the client with a notification such as notifications/tools/list_changed.

It only works if the server declared listChanged: true for that feature during capability negotiation. On receiving it, the client should call tools/list again to refresh its view.

{"jsonrpc":"2.0","method":"notifications/tools/list_changed"}

Typical triggers include enabling a plugin, a user gaining new permissions, or a database schema change that adds tables. Note that the notification carries no data; the client has to re-fetch.

Take quiz
After receiving notifications/tools/list_changed, a client should:
Restart the host application
Wait for the server to resend all tools automatically
Disable the server
Call tools/list again
A server may send list_changed only if it:
Uses stdio
Declared listChanged in its capabilities
Has no prompts
Returns outputSchema

30. Why must a stdio MCP server never write logs to stdout?

In stdio transport, stdout is the protocol channel. The client parses every line on it as a JSON-RPC message. A stray print("starting...") injects invalid text, and the client either errors out or silently drops the connection.

This is one of the most common reasons a new server "works in a terminal but not in Claude Desktop".

  1. Send diagnostics to stderr, or use the MCP logging utility.
  2. In Python, use logging configured to stderr, or print(..., file=sys.stderr).
  3. In Node, use console.error, not console.log.

Also watch third-party libraries that print banners to stdout on import.

Take quiz
In Node, which call is safe for debug output in a stdio MCP server?
console.error
console.log
process.stdout.write
console.table
Why does a stray print to stdout break the server?
It exceeds the token limit
It triggers sampling
The client parses stdout as JSON-RPC messages
It locks the stdin stream

31. How does pagination work in MCP list operations?

List methods such as tools/list, resources/list, and prompts/list use cursor-based pagination.

The server returns a page of items plus an opaque nextCursor string if more exist. The client passes that value back as cursor in the next request, repeating until no nextCursor appears.

// request page 2
{"jsonrpc":"2.0","id":3,"method":"resources/list",
 "params":{"cursor":"eyJvZmZzZXQiOjUwfQ=="}}

The cursor is opaque: clients must not parse or build it. Servers choose page size and encoding, which lets them back it with an offset, a keyset, or a database token.

Take quiz
What signals that more list results are available?
A hasMore boolean in the request
A nextCursor in the response
An HTTP Link header
A pageCount field
How should a client treat the cursor value?
As a base-10 page number it can increment
As a SQL fragment
As a file path
As an opaque string to send back unchanged

32. What are structured output and outputSchema in MCP tools?

By default a tool returns free-form content blocks, mostly text. Structured output lets a tool return machine-readable JSON as well, validated against an outputSchema that the tool declares in tools/list.

// tool definition
"outputSchema": { "type":"object",
  "properties": { "tempC": {"type":"number"}, "city": {"type":"string"} },
  "required": ["tempC","city"] }

// result
{ "structuredContent": { "city":"Charlotte", "tempC": 18 },
  "content": [{ "type":"text", "text":"{\"city\":\"Charlotte\",\"tempC\":18}" }] }

The result carries structuredContent for programs, and the same data serialized as text in content for backward compatibility. Clients can validate it, and the model gets a predictable shape instead of prose.

Take quiz
Where does a tool declare the JSON shape of its structured result?
resultFormat
returnSpec
outputSchema
schemaOut in initialize
Why also include the JSON as text in content?
Backward compatibility with clients that read only content
The spec bans structuredContent alone
To double the token cost
To bypass annotations

33. What are roots in MCP and why do they matter?

Roots are a client feature that tells a server which filesystem locations or URIs it should treat as its working boundaries, for example file:///home/user/projects/app.

The server asks with roots/list, and the client can notify it of changes via notifications/roots/list_changed when the user opens a different folder.

Roots are guidance, not a sandbox. A well-behaved server stays inside them and uses them to scope searches, but the protocol does not enforce it. If you need real isolation, apply OS-level controls such as containers or restricted file permissions.

Take quiz
What is the main purpose of roots?
Encrypting tool arguments
Ranking tools by popularity
Defining OAuth scopes
Telling a server which directories or URIs it should operate within
Do roots technically enforce file isolation?
Yes, the protocol blocks access outside roots
No, they are guidance and need OS-level controls for enforcement
Yes, but only on Windows
Only when using Streamable HTTP

34. How does MCP authorization work for remote servers?

For HTTP transports, MCP builds on OAuth 2.1. The MCP server acts as an OAuth resource server; a separate authorization server issues tokens.

sequenceDiagram
  participant C as MCP client
  participant S as MCP server
  participant A as Authorization server
  C->>S: request without token
  S-->>C: 401 plus WWW-Authenticate
  C->>S: fetch protected resource metadata
  C->>A: discover and authorize with PKCE
  A-->>C: access token
  C->>S: request with Bearer token
  1. The server returns 401 pointing to its Protected Resource Metadata (RFC 9728), which names the authorization server.
  2. The client discovers the authorization server's endpoints and registers or identifies itself.
  3. The user authorizes using PKCE, and the client requests a token bound to the server with the resource parameter.
  4. The client sends Authorization: Bearer ... on every request.

Authorization is optional, and stdio servers should take credentials from the environment instead.

Take quiz
What does a 401 from an MCP server point the client to?
Protected Resource Metadata describing the authorization server
A hard-coded vendor login page
A username and password form in JSON-RPC
The model provider's API key page
Which OAuth extension protects the authorization code flow for public clients?
HMAC signing of tool names
mTLS on stdio
PKCE
JWT embedding in prompts

35. Why does MCP require resource indicators in OAuth tokens?

Clients must send the resource parameter (RFC 8707) in authorization and token requests, naming the exact MCP server the token is for. The authorization server then issues a token whose audience is that server.

This prevents token misuse across services. Without it, a token obtained for Server A might be accepted by Server B, which could replay it, or a malicious server could take a token it received and use it elsewhere.

On the server side, you must validate the audience of every incoming token and reject tokens not issued for you. Audience binding makes a leaked or misdirected token far less useful.

A practical checklist for server authors: reject tokens with a missing or wrong audience, log the rejection reason, and never accept a token just because its signature is valid.

Take quiz
Which parameter binds a token to a specific MCP server?
scope_server
resource
aud_hint
target_host
What must an MCP server check on every incoming access token?
That the token is under 10 bytes
That it was issued by the client app
That it came over stdio
That the audience matches itself

36. What is token passthrough and why is it forbidden in MCP?

Token passthrough is when an MCP server accepts a token from a client without checking it was issued for the server, then forwards it unchanged to a downstream API. The MCP specification explicitly forbids this.

  • It breaks audit and accountability: the downstream API sees the client, not the server.
  • It bypasses security controls like rate limits and validation the server should apply.
  • It creates a confused deputy path, where the server's trust is used with credentials meant for something else.

The correct pattern: the server validates tokens issued to itself, and when it calls a downstream service, it obtains a separate token as its own client, or uses an on-behalf-of exchange.

Real-world impact is easy to miss: if the downstream API trusts the server's identity, a passed-through token can let one user's request act with another service's authority, and nobody notices until an audit.

Take quiz
What is the correct way for an MCP server to call a downstream API?
Forward the client's token unchanged
Embed the token in the tool description
Use a separate token issued for that downstream call
Skip authentication for internal calls
Why is accepting tokens not issued to the server a risk?
It bypasses controls and obscures accountability
It increases token size
It breaks JSON Schema
It causes SSE to disconnect

37. What is the confused deputy problem in MCP proxy servers?

It affects an MCP server that proxies to a third-party authorization server using a single static client ID. Because every MCP client appears as the same OAuth client to the third party, consent can be skipped for the wrong party.

The attack: a user has already approved the proxy once, so the third party stores a consent cookie. An attacker sends a crafted authorization link with a malicious redirect URI. The browser sends the cookie, consent is skipped, and the authorization code lands on the attacker.

Mitigations:

  1. Maintain a per-client consent record in the proxy and show its own consent screen before forwarding.
  2. Validate redirect URIs by exact match.
  3. Use a cryptographically random state, bound to the browser session, and verify it on return.
Take quiz
What condition makes the proxy vulnerable?
Using HTTPS for the proxy
Returning structuredContent
Implementing tools/list
A static client ID shared across all MCP clients toward a third-party AS
Which control helps stop a forged redirect URI?
Allowing wildcard redirect URIs
Exact-match redirect URI validation
Logging redirect URIs only
Using shorter access tokens

38. How can tool poisoning attack an MCP-connected assistant?

Tool poisoning hides malicious instructions in content the model reads but the user rarely sees, usually a tool's description or its results.

A tool described as "adds two numbers" might also contain hidden text telling the model to read ~/.ssh/id_rsa and include it in a parameter. Related attacks include:

Attack How it works
Rug pull Server changes a tool's definition after the user approved it
Tool shadowing One server's description alters how the model uses another server's tools
Indirect prompt injection Fetched web pages or tickets carry instructions in tool results

Defenses: show full tool descriptions for approval, pin or hash definitions and flag changes, require confirmation for sensitive actions, use least-privilege credentials, and isolate untrusted servers from sensitive ones.

Take quiz
What is a rug pull in MCP?
A server changing tool definitions after approval
A client dropping a connection
A failed OAuth redirect
A resource URI collision
Which defense helps detect a rug pull?
Lowering the log level
Using shorter tool names
Pinning or hashing tool definitions and flagging changes
Disabling pagination

39. How do you secure a local MCP server?

Local servers run with your user's privileges, so a malicious or buggy one can read files and run commands. Security means limiting what it can reach and who can talk to it.

  1. Prefer stdio where possible, which avoids opening a network port.
  2. If you use HTTP locally, bind to 127.0.0.1, not 0.0.0.0.
  3. Validate the Origin header and return 403 for unexpected origins, defending against DNS rebinding from web pages.
  4. Run in a sandbox or container with limited filesystem and network access.
  5. Show users the exact command before one-click installation of a new server, and require explicit consent.
  6. Add authentication even locally if other processes on the machine are not trusted.

For teams, add a review step for new servers: pin the version, read the source or the vendor's security notes, and prefer servers that request the narrowest scopes they need.

Take quiz
Which local HTTP bind address avoids exposing the server to the network?
0.0.0.0
127.0.0.1
255.255.255.255
The machine's public IP
Which attack does Origin validation defend against?
SQL injection
TLS downgrade
Cursor forgery
DNS rebinding from a browser page

40. What changed in the 2026-07-28 MCP specification?

The 2026-07-28 revision is the largest since launch. Its main theme is a stateless protocol core.

Area Change
Sessions Protocol-level sessions and the Mcp-Session-Id header are removed
Handshake Version and client capabilities travel in _meta on every request; servers describe themselves via server/discover
HTTP headers POST requests carry Mcp-Method and Mcp-Name so gateways can route without reading the body
Server-initiated asks A Multi Round-Trip Requests pattern replaces sampling, roots, and elicitation requests sent on an open stream
Tasks Moved out of the core into an official extension, using tasks/get and tasks/update
Notifications subscriptions/listen replaces the GET stream and resources/subscribe

Other updates include iss validation for authorization responses, trace context in _meta, and formal deprecation of HTTP+SSE. Check the official changelog before relying on any single detail.

Take quiz
Which header was removed along with protocol-level sessions?
MCP-Protocol-Version
Mcp-Method
Mcp-Session-Id
Accept
What does server/discover provide?
Supported versions, capabilities, and identity of the server
A list of active user sessions
OAuth tokens
Log files

41. How does a stateless MCP protocol help horizontal scaling?

Earlier HTTP deployments often needed sticky routing or a shared session store, because the initialize handshake created per-connection state that only one server instance knew about.

With the stateless design, each request carries what the server needs: protocol version and client capabilities in _meta, plus the Mcp-Method and Mcp-Name headers. Any replica can handle any request.

  • Plain round-robin load balancers work without session affinity.
  • Gateways and rate limiters can route or throttle by method and tool name from headers alone.
  • Scaling up or rolling a deployment no longer strands in-flight sessions.

When a server needs multi-step context, it should hand that state to the client in a requestState payload rather than hold it in memory.

One trade-off to plan for: anything that used to live in session memory, such as subscriptions or partial results, now needs an explicit design, either in client-held state or in your own datastore.

Take quiz
What lets any replica handle any request in the stateless design?
A shared GPU pool
Sticky cookies set by the client
A persistent WebSocket
Each request carries version and capabilities in _meta
Which headers help gateways route without parsing the body?
X-Tool-Weight and X-Model
Mcp-Method and Mcp-Name
Cache-Control and ETag
Content-MD5 and Via

42. What is the Multi Round-Trip Requests (MRTR) pattern?

In a stateless protocol, a server cannot keep a connection open to ask the client for something mid-call. MRTR solves this by finishing the current request with an input-required result, then letting the client retry with the answer.

sequenceDiagram
  participant C as Client
  participant S as Server
  C->>S: tools/call delete_project
  S-->>C: inputRequired with elicitation plus requestState
  C->>C: ask user for confirmation
  C->>S: tools/call again with answer plus requestState
  S-->>C: final result

The result lists what is needed (an elicitation, sampling, or roots request) and includes a requestState blob. The client gathers the input and re-sends the request with the answers and the same requestState, so the server can resume without remembering anything.

It replaces the previous approach of server-initiated requests on a live stream.

Take quiz
What does the server return when it needs more input in MRTR?
An input-required result with a requestState
An HTTP 301 redirect
A closed transport
A JSON-RPC notification only
What is requestState for?
Encrypting the token
Counting tool calls
Carrying context so the server can resume without stored session memory
Selecting a model

43. Explain the lifecycle of an MCP connection?

In the 2025-11-25 revision, a connection moves through three phases: initialization, operation, and shutdown.

sequenceDiagram
  participant C as Client
  participant S as Server
  C->>S: initialize with version, capabilities, clientInfo
  S-->>C: result with version, capabilities, serverInfo
  C->>S: notifications/initialized
  Note over C,S: Operation phase
  C->>S: tools/list, tools/call, resources/read
  S-->>C: results and notifications
  Note over C,S: Shutdown by closing transport
  1. Initialize: the client proposes a version and capabilities; the server answers with what it supports.
  2. Initialized: the client confirms with a notification, after which normal traffic is allowed.
  3. Operation: both sides exchange requests and notifications within negotiated capabilities.
  4. Shutdown: no special message; the client closes the transport (stdin for stdio, or the HTTP connection).

If versions are incompatible, the client should disconnect.

Take quiz
Which message tells the server that the client is ready for normal operation?
initialize/complete
notifications/initialized
session/start
ready/ack
How does shutdown happen over stdio?
A dedicated shutdown RPC is mandatory
The server sends a disconnect email
The host reboots
The client closes the streams to the process

44. Explain the execution flow of a tool call end to end?

A tool call spans the user, the host, the model, and the server.

sequenceDiagram
  participant U as User
  participant H as Host
  participant M as LLM
  participant S as MCP server
  H->>S: tools/list at connect
  S-->>H: tool definitions
  U->>H: Ask a question
  H->>M: message plus tool definitions
  M-->>H: tool call request
  H->>U: approval if required
  H->>S: tools/call name and arguments
  S-->>H: result content
  H->>M: tool result
  M-->>H: final answer
  H-->>U: response
  1. The host discovers tools once and gives their schemas to the model.
  2. The model decides to call one and emits a structured request.
  3. The host, not the model, performs the MCP call, usually after user approval.
  4. The result goes back to the model, which may call more tools or answer.

The model never talks to the server directly. That gap is where the host enforces approvals and limits.

Take quiz
Who sends the actual tools/call request to the server?
The model directly
The user's browser
The host, through its MCP client
The authorization server
Where can approval be enforced in this flow?
In the host, before it forwards the call
Inside the model weights
In the JSON-RPC library only
After the response is shown

45. What are MCP tasks and when should you use them?

Tasks let a request run as a durable, long-running job instead of holding a connection until it finishes. They were introduced as experimental in 2025-11-25, and the 2026-07-28 revision moved them into an official extension.

Instead of a final result, the server returns a task handle. The client then polls tasks/get for status and fetches the result when complete. The redesigned extension adds tasks/update so the client can send input to a running task.

Use tasks when work takes minutes or hours: report generation, large data exports, builds, or batch processing. Keep ordinary quick tools as plain calls, since tasks add polling overhead.

Also design for failure: store task results long enough for slow clients, return a clear failed status with a reason, and let clients cancel work that is no longer needed.

Take quiz
How does a client learn a task's progress?
By reading the server's stdout log
By opening a second MCP session
By waiting for an email
By polling tasks/get
Which workload fits tasks best?
A 10 ms arithmetic tool
A multi-minute data export
A static prompt template
Listing roots

46. How can you optimize MCP tool design for LLM context?

Every tool definition is loaded into the model's context, and every result is read by the model. Poor design wastes tokens and confuses tool selection.

  1. Keep the tool set small. Dozens of overlapping tools hurt accuracy. Merge near-duplicates or load groups on demand.
  2. Write precise descriptions that say when to use the tool and when not to.
  3. Use clear names and tight schemas with enums and descriptions on parameters.
  4. Return only what the model needs. Filter fields, summarize, and paginate instead of dumping a 5 MB JSON blob.
  5. Give actionable errors such as "Use YYYY-MM-DD", so the model can fix its own input.

Avoid mirroring a whole REST API one-to-one. Design tools around tasks the user wants done, not around endpoints.

Take quiz
Why is mirroring every REST endpoint as a tool often a mistake?
It bloats context and makes tool selection harder
REST cannot be wrapped by MCP
It violates JSON-RPC
It disables pagination
Best way to return a very large dataset from a tool?
Return everything in one text block
Write it to stdout
Filter, summarize, and paginate
Send it through roots

47. How do you troubleshoot an MCP server that will not connect?

Start by working out whether the failure is in launching, handshake, or transport.

  1. Run the command by hand exactly as in the config. Import errors and missing packages show up immediately.
  2. Check paths. Use absolute paths, and confirm the host can find node, python, or uv without your shell profile.
  3. Look for stdout pollution in stdio servers: prints, banners, or library warnings.
  4. Read host logs. Claude Desktop writes per-server MCP logs you can tail.
  5. Use MCP Inspector to confirm the server answers initialize and tools/list on its own.
  6. For remote servers, check 401/403 responses, CORS or Origin rules, and the protocol version header.

If Inspector works but the host does not, the cause is almost always the host config or environment variables.

Take quiz
A server works in Inspector but not in the host. First suspect?
The JSON-RPC spec version
Host config such as paths or environment variables
The model's temperature
Tool annotation values
Which mistake commonly breaks a stdio server silently?
Writing to stderr
Using type hints
Adding a docstring
Printing text to stdout

48. When would you choose MCP over direct API integration?

The decision comes down to how many places will use the integration and how dynamic it needs to be.

Choose MCP when Choose direct API calls when
Several AI apps or hosts need the same integration One application with a fixed workflow
Users bring their own tools or servers The tool set never changes
You want runtime discovery and standard auth You need tight latency and full control of every call
You want vendors to ship one server for everyone The integration is a single internal call

MCP adds a protocol layer, so for a single script calling one stable API, a plain function or SDK is simpler and faster. It pays off as the number of clients and tools grows.

Take quiz
Which situation favors MCP?
One cron job calling one endpoint
A static batch export
Many AI hosts reusing the same integration
A single hard-coded SQL query
Why might direct API calls win for one fixed workflow?
Less protocol overhead and simpler code
MCP cannot use HTTP
APIs are always faster to write for ten apps
MCP forbids private services

49. How do MCP clients register with an authorization server?

An MCP client must identify itself to the authorization server before it can run the OAuth flow, and servers cannot know every client in advance. The specification supports several approaches.

Method How it works
Client ID Metadata Documents (recommended) The client uses an HTTPS URL as its client_id; that URL hosts a JSON document with name, redirect URIs, and other metadata the auth server fetches
Dynamic Client Registration (RFC 7591) The client POSTs its metadata to a registration endpoint and receives a client_id; kept for compatibility
Pre-registration A developer registers the client manually and ships the client_id

Metadata documents avoid creating a new client record for every installation, which is a drawback of DCR. Clients should also store credentials keyed by the issuer so they are not reused with a different authorization server.

Take quiz
Which registration approach does the spec recommend for most MCP clients?
Emailing the vendor for a key
Hard-coded shared secret
Basic auth on every request
Client ID Metadata Documents
What is a client_id in a metadata document approach?
A random 4-digit PIN
An HTTPS URL hosting the client's metadata
The model name
A hash of the tool list

50. How do you observe and monitor a production MCP server?

Treat an MCP server like any other API service: you need logs, metrics, and traces, with some MCP-specific fields.

  1. Structured logs per call: tool name, request id, caller or client id, duration, and success or error flag. Never log tokens or full sensitive arguments.
  2. Metrics: call counts, latency percentiles, and error rates per tool, plus auth failures.
  3. Distributed tracing: the 2026-07-28 revision documents W3C Trace Context in _meta with traceparent, tracestate, and baggage, so a trace can span the host, your server, and downstream APIs.
  4. Audit trail for destructive tools: who triggered what, and whether a user approved it.

Watch per-tool error rates closely. A spike often means a schema the model keeps getting wrong, which is a design problem, not an outage.

Take quiz
Which keys carry W3C trace context in MCP _meta?
traceparent, tracestate, and baggage
x-trace-a, x-trace-b
mcp-span and mcp-trace
otel-id only
What should you avoid writing to production logs?
Tool names
Request durations
Access tokens and sensitive tool arguments
Error flags
«
»

Comments & Discussions