Skip to content

MCP - Server SSE Transport

Create MCP server file

server.py
# /// script
# requires-python = ">=3.11"
# dependencies = [
#     "mcp==1.21.0",
# ]
# ///

import argparse

from mcp.server.fastmcp import FastMCP  # type: ignore

mcp = FastMCP(
    name="Calculator",
    host="0.0.0.0",  # Only used for SSE transport (localhost)
    port=8333,  # Only used for SSE transport (set this to any port)
    stateless_http=True,
)


@mcp.tool()
def add(x: int, y: int) -> int:
    """Sum two integer numbers"""
    return x + y


if __name__ == "__main__":
    parser = argparse.ArgumentParser(
        description="Run MCP server with optional transport"
    )
    parser.add_argument(
        "--transport",
        choices=["stdio", "sse", "streamable-http"],
        default="stdio",
        help="Transport method to use (default: stdio)",
    )
    args = parser.parse_args()

    print(f"Running server with {args.transport} transport")
    mcp.run(transport=args.transport)

Install packages

1
2
3
!uv pip install -q \
    mcp==1.21.0 \
    nest-asyncio==1.6.0

Import packages

1
2
3
4
5
6
7
import asyncio

import nest_asyncio  # type: ignore
from mcp import ClientSession  # type: ignore
from mcp.client.sse import sse_client  # type: ignore

nest_asyncio.apply()  # Needed to run interactive python (Jupyter Notebooks)

Define client

async def main():
    async with sse_client("http://localhost:8333/sse") as (
        read_stream,
        write_stream,
    ):
        async with ClientSession(read_stream, write_stream) as session:
            await session.initialize()

            available_tools = await session.list_tools()
            print("Available tools:")
            for tool in available_tools.tools:
                print(f"  - {tool.name}: {tool.description}")

            result = await session.call_tool("add", arguments={"x": 2, "y": 2})
            print(f"2 + 3 = {result.content[0].text}")

Run the server before running the client

uv run server.py --transport sse

Run the client

if __name__ == "__main__":
    asyncio.run(main())
Available tools:

  - add: Sum two integer numbers

2 + 3 = 4