How to expose resources in MCP server
Quick answer
To expose resources in an
MCP server, define resource handlers and register them with the Server instance from the mcp SDK. Use the stdio_server or other transports to run the server, which listens for requests and exposes your resources to AI agents.PREREQUISITES
Python 3.8+pip install mcpBasic knowledge of Python async programming
Setup
Install the official mcp Python SDK and prepare your environment.
- Ensure Python 3.8 or higher is installed.
- Install the MCP SDK via pip.
pip install mcp Step by step
Create a Python script that defines resource handlers, registers them with an mcp.server.Server instance, and runs the server using stdio_server. This example exposes a simple resource that returns a greeting.
import asyncio
from mcp.server import Server
from mcp.server.stdio import stdio_server
async def greet_resource(params):
name = params.get("name", "world")
return {"message": f"Hello, {name}!"}
async def main():
server = Server()
# Register resource named 'greet'
server.register_resource("greet", greet_resource)
# Run the server with stdio transport
await stdio_server(server)
if __name__ == "__main__":
asyncio.run(main()) Common variations
You can expose multiple resources by registering more handlers with server.register_resource. For async resource handlers, define them as async functions. MCP supports different transports like stdio_server (default) or SSE-based servers for web integration.
import asyncio
from mcp.server import Server
from mcp.server.stdio import stdio_server
async def add_resource(params):
a = params.get("a", 0)
b = params.get("b", 0)
return {"result": a + b}
async def main():
server = Server()
server.register_resource("greet", lambda p: {"message": "Hello!"})
server.register_resource("add", add_resource)
await stdio_server(server)
if __name__ == "__main__":
asyncio.run(main()) Troubleshooting
- If the server does not start, ensure you are running the script in a terminal that supports stdio communication.
- For resource errors, verify your handler functions accept a single
paramsdict and return a dict. - Use
asyncio.run()to run the async main function properly.
Key Takeaways
- Use the official
mcpPython SDK to create and expose resources in an MCP server. - Register resource handlers with
Server.register_resourceand run the server withstdio_server. - Resource handlers must accept a
paramsdictionary and return a dictionary response. - You can expose multiple resources and use async functions for concurrency.
- Troubleshoot by verifying environment compatibility and handler function signatures.