Modular Model Context Protocol hub connecting Resources, Tools, and Prompts to an AI client interface
MCP 16 min read Updated

MCP Resources, Tools, and Prompts: Complete Reference (2026)

Master Model Context Protocol primitives. Learn when to use Resources, Tools, and Prompts with Python FastMCP code, Streamable HTTP, and JSON-RPC schemas.

MCP Model Context Protocol FastMCP JSON-RPC AI Integration

The Model Context Protocol divides every server capability into three primitives: Resources, Tools, and Prompts, each governed by a strict control boundary. Moving read-only data out of dynamic Tools and into URI-addressed Resources cuts multi-turn prompt overhead by up to 35% and prevents 200-tool catalogs from burning 150,000+ context tokens.

Engineering teams often default to wrapping every database read, configuration lookup, and workflow template as an executable tool. That shortcut inflates JSON Schema token costs, degrades model tool-selection accuracy, and weakens permission boundaries between host applications and autonomous models.

Key Takeaways

  • The Model Context Protocol separates server capabilities into three control domains: Resources (application-controlled), Tools (model-controlled), and Prompts (user-controlled).
  • MCP Resources expose read-only context via RFC 6570 URI templates with zero side effects, reducing prompt overhead by up to 35% compared to tool polling loops.
  • Heavy MCP Tool schemas consume 800 to 1,200+ tokens each, making progressive tool discovery or code-mode execution essential once catalogs exceed 20 tools.
  • Modern MCP servers use stateless Streamable HTTP POST requests with request-scoped SSE streams, replacing legacy stateful Mcp-Session-Id connections.

This reference breaks down MCP resources tools and prompts across control authority, JSON-RPC 2.0 wire payloads, FastMCP Python implementations, token economics, and production security.

MCP Architecture and the Three-Primitive Control Model

Model Context Protocol primitives enforce a clean separation of concerns between the host application, the language model, and the end user. Rather than giving an LLM unrestricted authority over every endpoint, the specification assigns each primitive to a single initiating party.

Five-column MCP topology showing Host, Client Session, Streamable HTTP, Primitives Router, and Backend Figure 1: Control and execution topology separating application-controlled Resources, model-controlled Tools, and user-controlled Prompts over JSON-RPC 2.0.

Host, Client, and Server Isolation Boundaries

MCP operates on a decoupled Host-Client-Server topology. The Host (such as Claude Desktop, Cursor IDE, or a custom agent runner) manages user permissions, security policies, and LLM orchestration, while instantiating one dedicated Client per Server in a strict 1:1 session.

Each Server remains lightweight and isolated from the rest of the system. An MCP server cannot read the full conversation history or inspect data returned by sibling servers, receiving only the explicit requests routed by the Host.

For a deeper look at capability negotiation and lifecycle initialization, review our Model Context Protocol architecture overview.

MCP Resources vs Tools vs Prompts Comparison Matrix

Deciding between mcp resources vs tools or mcp prompts vs tools comes down to who triggers the capability and whether execution mutates state.

Primitive Type Controller JSON-RPC Methods State Side Effects Primary Use Case
Resources Host Application resources/list, resources/read None (Read-only) Database schemas, configs, logs, docs
Tools Language Model tools/list, tools/call Yes (State mutation) API writes, SQL queries, file edits
Prompts Human User prompts/list, prompts/get None (Templated) Slash commands, code reviews, triage

Client support also varies by primitive. Every MCP client implements Tools, whereas Resources and Prompts depend on how the host UI exposes file attachments and slash-command menus.

MCP Resources: Read-Only Context and URI Templates

MCP resources are passive, read-only data endpoints addressed by standardized URI strings (uri, name, mimeType). Because the host application controls when a Resource is attached to the context window, the model gains deterministic background knowledge without burning reasoning turns on function calls.

When deciding when to use mcp resource vs tool, apply a strict rule: if the endpoint only returns existing data without side effects, expose it as a Resource. Benchmarks show that reading static schemas via Resources keeps response latency under 50 ms while cutting prompt overhead by 35% compared to multi-turn tool loops, as detailed in the Model Context Protocol Resources Specification.

Static URIs vs RFC 6570 Dynamic Resource Templates

Servers expose fixed assets such as config://app/settings as static resources, while parameterized data uses RFC 6570 URI templates such as users://{user_id}/profile. In Python, FastMCP extracts path variables from the URI template and casts them automatically using standard type annotations.

from mcp.server.fastmcp import FastMCP

mcp = FastMCP("InfrastructureService")

# Static read-only resource
@mcp.resource("config://app/settings", mime_type="application/json")
def get_application_settings() -> str:
    """Expose immutable service configuration to the host."""
    return '{"environment": "production", "max_connections": 100, "timeout_ms": 250}'

# Dynamic RFC 6570 resource template
@mcp.resource("users://{user_id}/profile", mime_type="application/json")
def get_user_profile(user_id: int) -> str:
    """Fetch a read-only user profile by numeric ID."""
    return f'{{"user_id": {user_id}, "role": "platform_engineer", "tier": "enterprise"}}'

In this fastmcp resource template example, requesting users://42/profile triggers get_user_profile(user_id=42) with strict integer coercion. For relational schemas and query-backed URIs, follow our MCP database integration tutorial.

Subscriptions and Change Notifications

Modern MCP servers notify connected hosts when underlying resource state changes. Instead of polling resources/read repeatedly, clients open a subscriptions/listen request-scoped stream and react to notifications/resources/updated events whenever files, logs, or schema versions shift.

[!TIP] Attach caching hints (ttlMs) on slow-changing Resources like OpenAPI specs or database schemas so host applications reuse local snapshots across turns without re-fetching.

MCP Tools: Model-Controlled Execution and Annotations

MCP tools are executable functions that the language model discovers via tools/list and invokes autonomously via tools/call. Unlike passive Resources, Tools let the model compute values, call external REST APIs, run SQL queries, or mutate filesystem state.

Every tool registers a JSON Schema input contract alongside natural-language parameter descriptions. Understanding the architectural boundary between decoupled MCP servers and native provider schemas is covered in our MCP vs function calling comparison.

JSON Schema Input Validation and Error Handling

Production servers validate tool arguments before touching downstream systems. FastMCP inspects Python type hints and Pydantic models to generate strict schemas, returning structured isError: true payloads when validation or policy checks fail so the model can self-correct without crashing the host session.

from pydantic import Field

@mcp.tool()
def execute_sql_query(
    query: str = Field(description="Read-only SELECT statement to run against analytics."),
    limit: int = Field(default=50, ge=1, le=500, description="Maximum rows to return.")
) -> str:
    """Run a bounded SQL query against the reporting warehouse."""
    normalized = query.strip().upper()
    if not normalized.startswith("SELECT"):
        raise ValueError("Policy violation: only SELECT statements are permitted.")
    return f"Executed bounded query (limit={limit}). Returned 18 rows in 34 ms."

Using Field constraints (ge=1, le=500) enforces numeric bounds directly in the JSON Schema exported to the client.

Tool Annotations and Elicitation Flows

The Model Context Protocol Tools Specification defines behavioral annotations such as readOnlyHint, destructiveHint, and idempotentHint. These metadata flags help host UIs decide whether to prompt a human for confirmation before executing an action.

from mcp.types import ToolAnnotations

@mcp.tool(
    annotations=ToolAnnotations(
        readOnlyHint=False,
        destructiveHint=True,
        idempotentHint=False,
        openWorldHint=True
    )
)
def purge_stale_cache(namespace: str) -> str:
    """Purge expired cache keys from a production Redis namespace."""
    return f"Purged expired keys in namespace '{namespace}'."

By specification, MCP clients must treat all mcp tool annotations readonlyhint and destructive flags as untrusted hints unless the server itself is cryptographically verified or explicitly allowlisted. When a tool needs missing user input mid-execution, modern servers use elicitation (Multi Round-Trip Requests) to request structured credentials or approvals cleanly through the host UI.

MCP Prompts: User-Controlled Workflows and Templates

MCP prompts are reusable, parameterized interaction templates authored by the server and triggered explicitly by a human user. Hosts discover them via prompts/list and instantiate them via prompts/get, typically surfacing each template as a slash command in the chat bar.

While developers often search for a chatgpt mcp prompt template or team-wide slash command, the underlying mechanism is identical across compliant hosts. Prompts standardize recurring workflows such as security audits, incident post-mortems, and pull request reviews without requiring users to copy-paste long instructions, as specified in the Model Context Protocol Prompts Specification.

Parameterized Slash Commands and Resource Embedding

Understanding how to build mcp prompt templates effectively means combining typed user arguments with embedded Resource references. Because prompts/get returns structured message arrays (UserMessage, AssistantMessage), a single template can inject live logs or configuration URIs directly alongside review instructions.

from mcp.server.fastmcp.prompts import base

@mcp.prompt()
def incident_triage(service_name: str, severity: int = 2) -> list[base.Message]:
    """Generate a structured incident triage prompt with embedded service logs."""
    return [
        base.UserMessage(
            f"Triage a Severity-{severity} incident on '{service_name}'. "
            f"Inspect resource logs://{service_name}/errors before proposing a rollback."
        ),
        base.AssistantMessage(
            "I will read the service error resource first and check recent deployment deltas."
        ),
    ]

Raw MCP prompt arguments travel over the wire as strings, but FastMCP coerces severity: int = 2 automatically using Python type hints.

Cross-Client Prompt Template Portability

Centralizing mcp prompt templates on a shared server guarantees consistent reasoning steps across Claude Desktop, Cursor IDE, and custom internal agents. When an engineering team updates a compliance checklist on the server, every connected client receives the updated workflow on the next prompts/list call.

For host-side configuration, permissions, and slash-menu discovery details, see our Claude Desktop MCP setup guide.

JSON-RPC 2.0 Wire Format and Streamable HTTP Transport

Under the hood, every json-rpc 2.0 mcp message uses standardized request, response, and notification envelopes defined in the Model Context Protocol Specification Repository on GitHub. Understanding the raw wire payloads makes debugging client-server mismatches straightforward.

Wire-Format Payloads Across All Three Primitives

Clients issue distinct JSON-RPC methods for each primitive, passing URI identifiers for Resources, structured arguments for Tools, and named parameters for Prompts.

{
  "jsonrpc": "2.0",
  "id": 101,
  "method": "resources/read",
  "params": {
    "uri": "users://42/profile"
  }
}

Tool execution uses tools/call with a name and arguments map, while prompt instantiation calls prompts/get with stringified arguments.

{
  "jsonrpc": "2.0",
  "id": 102,
  "method": "tools/call",
  "params": {
    "name": "execute_sql_query",
    "arguments": {
      "query": "SELECT service, p95_ms FROM telemetry",
      "limit": 25
    }
  }
}

Keeping these wire shapes in mind helps when inspecting gateway logs or writing integration tests against raw MCP endpoints.

Stdio vs Stateless Streamable HTTP Transport

Comparing stdio vs streamable http mcp comes down to deployment topology. Stdio launches the server as a local child process communicating over standard input and output pipes, making it ideal for single-user desktop editors.

For remote cloud services, the stateless streamable http mcp transport (standardized in the 2026 protocol overhaul) replaced legacy long-lived GET SSE connections and stateful Mcp-Session-Id handshakes. Every HTTP POST request now acts as an independent JSON-RPC container carrying protocol version and capability metadata inside _meta:

  • Stateless Horizontal Scaling: Load balancers can route consecutive POST calls to any container replica without sticky sessions.
  • Request-Scoped SSE: Servers reply with either a single JSON payload or an SSE stream scoped strictly to that HTTP POST request.
  • Proxy Header Mirroring: Using x-mcp-header, servers can mirror key parameters into Mcp-Param-{name} HTTP headers so WAFs and API gateways inspect traffic without parsing deep JSON bodies.

Complete FastMCP Python Server Implementation

Building a production fastmcp python server requires combining all three primitives with shared Pydantic validation, context logging, and clean transport configuration using the Model Context Protocol Python SDK on GitHub.

Unified Production Server with Typed Primitives

The following unified server exposes a dynamic Resource template for cluster telemetry, a Tool with safety annotations, and a Prompt template for incident diagnosis.

from mcp.server.fastmcp import FastMCP, Context
from mcp.types import ToolAnnotations
from pydantic import Field

app = FastMCP("ProductionMonitor")

# 1. Application-Controlled Resource Template
@app.resource("status://cluster/{region}/health", mime_type="application/json")
def cluster_health(region: str) -> str:
    """Expose read-only regional cluster telemetry."""
    return f'{{"region": "{region}", "healthy_nodes": 8, "cpu_utilization_pct": 34.2}}'

# 2. Model-Controlled Tool with Safety Annotations
@app.tool(
    annotations=ToolAnnotations(
        readOnlyHint=False,
        destructiveHint=True,
        idempotentHint=True
    )
)
async def restart_worker_node(
    node_id: str = Field(pattern=r"^worker-[a-z0-9-]+$"),
    ctx: Context = None
) -> str:
    """Gracefully drain and restart an unhealthy worker node."""
    if ctx:
        await ctx.info(f"Initiating graceful restart for {node_id}")
    return f"Node {node_id} drained and restarted in 180 ms."

# 3. User-Controlled Prompt Template
@app.prompt()
def diagnose_node(node_id: str, region: str = "us-east-1") -> str:
    """Standardized diagnostic runbook for worker node degradation."""
    return (
        f"Read status://cluster/{region}/health first. "
        f"Correlate memory pressure before invoking restart_worker_node on {node_id}."
    )

if __name__ == "__main__":
    app.run(transport="streamable-http")

For full project scaffolding, virtual environment setup, and client registration steps, follow our guide to build an MCP server in Python.

Context Injection and Structured Logging

Injecting ctx: Context into async Tool handlers gives the server access to ctx.info(), ctx.warning(), and progress reporting over the active transport. Clients such as Claude Desktop and Cursor IDE surface these log notifications in real time without polluting the tool’s final return string.

Token Overhead, Latency Benchmarks, and Progressive Discovery

Naive MCP deployments suffer from an architectural bottleneck known as the “MCP Tax” or mcp context window explosion. Because standard clients call tools/list at startup and inject every JSON Schema into the system prompt, large tool catalogs rapidly exhaust token budgets.

Bar chart comparing MCP token overhead across Eager Loading, Progressive Discovery, and Code-Mode Sandbox Figure 2: Initial system prompt token overhead and tool-selection accuracy across a 200-tool MCP stack on a 200K context window.

The MCP Tax: Tool Schema Token Math

Simple health-check tools consume roughly 100 tokens, whereas heavy enterprise tools with nested arrays and verbose parameter descriptions consume 800 to 1,200+ tokens per tool. Connecting 10 MCP servers with 200+ tools burns 150,000+ tokens before a single user prompt is processed, consuming 75% to 80% of a 200K context window on models like Claude Sonnet 5.5.

Overloading the context window also hurts reasoning quality. Empirical benchmarks show tool-selection accuracy drops from roughly 74% to 49% when irrelevant tool definitions flood attention layers, while poorly structured descriptions increase multi-step execution chatter by over 60%.

Progressive Tool Discovery and Code-Mode Execution

Comparing eager loading vs progressive tool discovery highlights three clear architectural tiers for mcp tool token overhead optimization.

Loading Strategy Initial Schema Tokens (200 Tools) Selection Accuracy Impact Best Production Fit
Eager Loading (tools/list) 150,000+ tokens Degrades sharply (~49% at 200 tools) Small stacks (< 15 tools total)
Progressive Tool Discovery < 1,500 tokens (meta-tool stub) High (~74%+ with targeted retrieval) Enterprise multi-server gateways
Code-Mode Sandbox Execution 500 to 2,000 tokens Highest (50 to 80% total token savings) Batch workflows & data pipelines

In progressive tool discovery, the host hides the full catalog behind a lightweight search_tools meta-tool and loads schemas only on demand. Keeping static definitions under 5% of the context window preserves reasoning accuracy.

In Code Mode, the model writes a short Python or Starlark orchestration script inside a sandbox that calls local MCP bindings directly. Only the compact final result returns to the context window, cutting token inflation by 50 to 80%.

Production Security and Troubleshooting Common MCP Failures

Exposing local filesystems, databases, and cloud APIs to autonomous models expands the attack surface. Applying mcp security best practices requires defending against supply-chain tampering in tools/list metadata as well as transport-layer misconfigurations.

Five-tier MCP security defense matrix covering Gateway mTLS, Manifest Pinning, Sanitization, Sandboxing, and Audit Figure 3: Five-tier defense-in-depth matrix protecting MCP servers against tool poisoning, rug pulls, and unauthorized state mutations.

Mitigating Tool Poisoning (OWASP MCP03) and Rug Pulls

Two supply-chain attacks dominate production MCP incidents. Tool Poisoning (OWASP MCP03) hides malicious instructions inside a tool’s description or parameter schema; because the model treats tool definitions as trusted context, poisoned metadata can silently instruct the agent to exfiltrate local secrets.

Rug Pull Attacks (such as CVE-2025-54136) occur when a third-party MCP package behaves safely during initial approval, then silently swaps its schema or handler logic in a subsequent update. To prevent mcp tool poisoning rug pull exploits:

  • Pin Cryptographic Manifest Hashes: Lock server versions and verify SHA-256 hashes of tools/list payloads in CI/CD before loading them into host clients.
  • Route Through an MCP Gateway: Terminate mutual TLS (mTLS), OAuth 2.1 scopes, and Role-Based Access Control (RBAC) at a centralized proxy rather than exposing raw Stdio or HTTP endpoints.
  • Inject Secrets at Runtime: Never pass API keys or OAuth tokens as tool parameters; fetch credentials from a backend vault during execution.
  • Sanitize Descriptions and Outputs: Strip hidden markdown directives from tools/list responses and treat all tool return values as untrusted data.

Troubleshooting Schema Drift, Injection, and Transport Timeouts

When production agents misbehave or stall, isolate the failure using these three diagnostic runbooks:

  1. Error: mcp schema drift rug pull (Unexpected Argument Calls or Outbound Requests): Diff the live tools/list JSON against your pinned baseline manifest and audit pip or npm lockfiles for unpinned auto-updates.

  2. Error: mcp tool poisoning injection (Agent Executes Unprompted Actions): Inspect raw tools/list description fields and recent tool outputs for embedded instruction tags, then quarantine the offending server in an isolated container.

  3. Error: mcp broken pipe stdio timeout (Connection Drops Mid-Execution): Verify that Stdio servers write logs strictly to stderr (never stdout, which corrupts JSON-RPC framing) and migrate remote workloads to stateless streamable http mcp behind a reverse proxy.

Frequently Asked Questions

When should I use an MCP Resource instead of an MCP Tool?

Use an MCP Resource whenever the server exposes read-only data, database schemas, or system logs that produce zero side effects. Reserve MCP Tools for actions that mutate state, execute computations, or require the model to supply dynamic runtime arguments.

How do MCP Prompts differ from system prompts and Tools?

MCP Prompts are user-controlled slash-command templates stored on the server and explicitly triggered by a human via prompts/get. System prompts are static host instructions, whereas Tools are functions invoked autonomously by the language model.

How much context window overhead do MCP tool definitions consume?

A simple tool schema uses roughly 100 tokens, whereas complex production tools consume 800 to 1,200+ tokens each. Eagerly loading 200+ tools across multiple servers burns over 150,000 tokens and degrades tool-selection accuracy.

What replaced legacy SSE transport in modern MCP servers?

Stateless Streamable HTTP replaced legacy long-lived GET SSE connections and stateful Mcp-Session-Id handshakes. Clients now send independent HTTP POST requests with _meta capability fields and receive either JSON or request-scoped SSE streams.

How does FastMCP handle RFC 6570 URI templates and prompt arguments?

FastMCP parses path variables from RFC 6570 URI templates such as users://{user_id}/profile and casts them using Python type annotations. It also coerces incoming string prompt arguments into typed Python primitives automatically.

How do you prevent tool poisoning and rug pull attacks in MCP?

Pin cryptographic hashes of server manifests and tool schemas before deployment so silent upstream updates fail verification immediately. Route traffic through an MCP gateway that sanitizes tool descriptions, injects vault credentials at runtime, and treats all tool annotations as untrusted.

MCP Model Context Protocol FastMCP JSON-RPC AI Integration

Found this helpful? Share it with others.

Raj, Founder, AI Agents Kit at AI Agents Kit

Raj

Founder, AI Agents Kit

Raj is the founder of AI Agents Kit, where he writes hands-on guides on AI agents, agent frameworks, Model Context Protocol (MCP), prompt engineering and developer tooling. He builds and tests the tools he covers and focuses on practical, working examples for developers and teams adopting agentic AI.

AI Agents LLMs Prompt Engineering Python TypeScript