Building SSE Servers
local graph
Chapter 4 — Building SSE Servers
Section titled “Chapter 4 — Building SSE Servers”So far, you’ve seen how you can build MCP servers using STDIO as transport. That’s a great choice of transport for servers meant to run locally. However, if you want to connect to servers remotely via HTTP or if you want responses from LLMs streamed, then there’s another transport called Server-Sent Events (SSE) better suited to this scenario.
In this chapter, we’ll focus on building and testing MCP servers using SSE as transport.
The chapter covers the following topics:
- SSE concepts
- Creating an SSE server as a web app
- Testing with SSE
- Creating an SSE server
Let’s dive into the details of SSE and how to build a server using it.
SSE concepts
Section titled “SSE concepts”There are some concepts we need to understand before we can start building our server. First off, a server using SSE as transport is a server that can be accessed via HTTP. That means, even if it can run locally, it can also be accessed remotely. The implications of this are that this is a server that we need to expose using a web server.
SSE is a standard for unidirectional communication from server to client over a single, long-lived HTTP connection. It allows servers to push real-time updates to clients without requiring the client to poll for changes. Here are some more details:
- Protocol: SSE uses standard HTTP with the MIME type text/event-stream
- Client API: The browser uses the EventSource API to receive events
- Format: Messages are sent as plain text with fields such as
event,data, andid, each terminated by two endlines
It’s typically used for dashboard-like applications where real-time updates are crucial.
In MCP, SSE is split up into two parts: the part where we connect to the server and perform initialization (e.g., handshake), and a message part where we apply messages to the server that ends up reading or writing data. So, we need to implement the following endpoints:
- SSE endpoint: This endpoint is used as a way to handshake the connection between the client and the server. By sending a request to this endpoint, the client will receive a response that will keep the connection open.
- Message endpoint: This endpoint is what’s used to route messages to the MCP server and its features.
It should be said that, depending on the chosen runtime and SDK, you may need to implement these endpoints yourself, but for some runtimes, it happens under the hood. Regardless, it’s good to know how it works and what the endpoints are doing.
Creating an SSE server as a web app
Section titled “Creating an SSE server as a web app”The big difference compared to using the STDIO transport is that we need to expose an SSE server as a web application. Depending on whether we use Python or TypeScript, that means we need to implement the necessary HTTP endpoints.
Specifically for Python, we need to leverage a framework supporting Asynchronous Server Gateway Interface (ASGI). ASGI is a specification that allows Python web frameworks to handle asynchronous and synchronous code, making it ideal for modern web applications. Let us look at Starlette.
Starlette
Section titled “Starlette”Starlette is a lightweight ASGI framework that we will use to build our SSE server. Previously, we mentioned endpoints that needed to be implemented, and Starlette will help us with that. It provides a simple way to create an ASGI application and handle routing, middleware, and other features.
Let’s look at how Starlette works and then explain in more detail how to build an SSE server using it.
A typical application using Starlette will look like this:
from starlette.applications import Starlettefrom starlette.responses import JSONResponsefrom starlette.routing import Routeasync def homepage(request): return JSONResponse({'hello': 'world'})app = Starlette(debug=True, routes=[ Route('/', homepage),])In the preceding code, we’ve done the following:
- Imported the necessary modules from Starlette
- Defined a simple
homepagefunction that returns a JSON response
The next step is to run it. We can use a server such as uvicorn to run our Starlette application:
uvicorn main:appHere, we are using uvicorn to run the application. The syntax is uvicorn <filename>:<name of app instance>. In this case, the filename is main.py and the app instance is app.
Starlette and MCP
Section titled “Starlette and MCP”To use Starlette with MCP, we can create the following application:
from starlette.applications import Starlettefrom starlette.routing import Mount, Hostfrom mcp.server.fastmcp import FastMCPmcp = FastMCP("My App")# Mount the SSE server to the existing ASGI serverapp = Starlette( routes=[ Mount('/', app=mcp.sse_app()), ])# or dynamically mount as hostapp.router.routes.append(Host('mcp.acme.corp', app=mcp.sse_app()))In the preceding code, we are doing the following:
- Importing the necessary modules from Starlette and MCP.
- Creating an instance of
FastMCPwith the name of the application. Note especially themcp.sse_app()method. This is the method that creates the SSE server and mounts it to the existing ASGI server. What happens under the hood is that it creates the SSE endpoint and the message endpoint for you.
If you’re interested in diving into the Python SDK to see how this is done, you can check https://github.com/modelcontextprotocol/python-sdk/blob/e80c0150e1c2e45f66195d3cf7d209be31ce6e5d/src/mcp/server/fastmcp/server.py#L747, and you will see the following code as part of the sse_app() method:
routes.append( Route( self.settings.sse_path, endpoint=sse_endpoint, methods=["GET"], ))routes.append( Mount( self.settings.message_path, app=sse.handle_post_message, ))As you can see, both the SSE endpoint and the message endpoint are created for you by calling the sse_app() method.
What about features using SSE, do they work the same way as STDIO? Yes, they do. You can use the same decorators and methods to create features. The only difference is that you need to use the mcp.sse_app() method to create the SSE server and mount it to the existing ASGI server.
Testing with SSE
Section titled “Testing with SSE”There are differences, though, when it comes to how testing tools using SSE work. Let’s list the differences:
- Inspector tool: The Inspector tool is a command-line tool that allows you to test your server using both a visual interface and a command-line interface. The difference between STDIO and SSE is that you need to specify Transport Type as SSE and URL as
http://<address>:<port>/sse. This is something you need to do when using the visual interface.
For the CLI mode, you need to specify a URL instead of how to run the server. So, the following command will work, provided you have the server running at localhost:8000:
npx @modelcontextprotocol/inspector --cli http:localhost:8000/sse --method tools/listLet’s see the difference in the visual interface:

Figure 4.1 – Inspector tool, visual mode, SSE
Figure 4.1 – Inspector tool, visual mode, SSE
Note how Transport Type is set to SSE and URL is set to http://localhost:8000/sse. Remember with STDIO how we didn’t have a URL field and rather a field to specify how to run the server? This is the difference between STDIO and SSE when it comes to the Inspector tool.
- Web client: Because the SSE server is running on HTTP, you can use any HTTP client to test it. This includes tools such as Postman, cURL, or even your web browser. To use cURL, you can use the following command:
- Get the session ID:
export MCP_SERVER="http://0.0.0.0:8000"curl "${MCP_SERVER}/sse"
\`\`\`textevent: endpointdata: http://localhost:5001/messages?session_id=<my session id>\`\`\` - Get the session ID:
- Use the session ID to send a message to the server on the message endpoint.
Ensure you send this in another terminal instance. The answer to this request will appear in the first terminal though.
export MCP_ENDPOINT="http://localhost:8000/messages?session_id=<my session id>"- Send a message to the server, such as listing tools, in a separate terminal from the one that you sent the initialize request to.
curl -X POST "${MCP_ENDPOINT}" -H "Content-Type: application/json" -d '{"jsonrpc": "2.0","id": 1,"method": "tools/list"}'
So, yes, it’s possible to do this using cURL, but it’s a bit cumbersome, which makes the inspector tool a great choice for testing your server – also for SSE.
Creating an SSE server
Section titled “Creating an SSE server”Okay, so we understand the concepts of SSE and how to build a server, and even how our testing tools work and are different from STDIO. Now it’s time to build our own SSE server. We’ll learn how to do the following:
- Set up a project
- Add the server code
- Test the server
Create the project
Section titled “Create the project”Let’s create a new project like so:
- Create a virtual environment:
python -m venv venv
- Activate the virtual environment:
source venv/bin/activate
- Install the dependencies:
pip install "mcp[cli]"
There, you should be all set up to start building your SSE server.
Add the server code
Section titled “Add the server code”Now add the following code to your project:
In server.py, add the following code:
from starlette.applications import Starlettefrom starlette.routing import Mount, Hostfrom mcp.server.fastmcp import FastMCPmcp = FastMCP("My App")# Mount the SSE server to the existing ASGI serverapp = Starlette( routes=[ Mount('/', app=mcp.sse_app()), ])In the preceding code, we’ve done the following:
- Imported the necessary modules from Starlette and MCP.
- Created an instance of
FastMCPwith the name of the application. Note especially themcp.sse_app()method helping us mount the endpoints for SSE handshake and message routing.
Add features
Section titled “Add features”The next step is about adding features to your server. As mentioned, there’s no difference between STDIO and SSE when it comes to features. You can use the same decorators and methods to create features.
In the same file, add the following code:
@mcp.tool()def add(a: int, b: int) -> int: """calc""" return a + bYou’ll get the chance to add more features later in the assignment, but for now, you have a working server with a feature that adds two numbers.
Run it
Section titled “Run it”The next step is to run the server.
- Start the server using the command line:
uvicorn main:app --port 3000
The syntax is uvicorn <filename>:<app>, where <filename> is the name of your Python file and <app> is the name of your ASGI app.
- Start the Inspect tool using the command line:
mcp dev server.py
Set the following fields in the UI:
- Transport Type: SSE
- URL:
http://localhost:3000/sse
Try your features as usual, but now using the SSE server.
Test it
Section titled “Test it”We will test our server in three different ways.
- Inspector tool, as a visual interface: This is a good way to test your server and see how it works
- Inspector tool with the CLI option: The CLI option provides a response directly in the command line. This is a good way to test your servers in, for example, CI/CD pipelines.
- Using a client: Here, we’ll use cURL to test that our server responds to requests. This is a good way to quickly test your server.
Inspector tool
Section titled “Inspector tool”Let’s try the Inspector tool using the visual interface. Start the Inspector tool using the command line:
Run the following command in a new terminal window with the server running.
npx @modelcontextprotocol/inspectorSet the following fields in the UI:
- Transport Type: SSE
- URL:
http://localhost:3000/sse
In the Tools section, select add and type the input for a and b:
510Inspector tool as a CLI option
Section titled “Inspector tool as a CLI option”For this option, we’ll use the Inspector tool like before, but with the added --cli option to run it in CLI mode. Remember, we will get the response directly in the command line as opposed to the UI:
npx @modelcontextprotocol/inspector --cli http://127.0.0.1:3000/sse --method tools/call --tool-name add --tool-arg a=5 --tool-arg b=10You should see the following output:
{ "content": [ { "type": "text", "text": "15" } ], "structuredContent": { "result": 15 }, "isError": false}curl command
Section titled “curl command”To test with cURL, there are three calls we need to make:
- A call to
/sse. This should give us a session ID back:curl http://127.0.0.1:3000/sse
You should see an output similar to the following:
event: endpointdata: /messages/?session_id=53ddee76d5ec4b4aaa9420f24462210a- A call to
/messageswith the session ID also containing the initialized MCP message.
The following command should be run in a separate terminal.
curl -X POST "http://127.0.0.1:3000/messages/?session_id=53ddee76d5ec4b4aaa9420f24462210a" -H "Content-Type: application/json" -d '{ "jsonrpc": "2.0", "method": "notifications/initialized"}'This will tell the server we’re ready to communicate.
- Feature ask: the following
curlcommand is asking to list tools on the MCP Server.
The following command should be run in the same terminal as the previous command.
curl -X POST "http://127.0.0.1:3000/messages/?sessionId=53ddee76d5ec4b4aaa9420f24462210a" -H "Content-Type: application/json" -d '{ "jsonrpc": "2.0", "id": 1, "method": "tools/list", "params": {}}'You should now see a response in the first terminal you used when you initialized the connection. It should look similar to the following:
event:messagedata: {"result":{"tools":[{"name":"products","description":"get products by category","inputSchema":{"type":"object","properties":{"category":{"type":"string"}},"additionalProperties":false,"$schema":"http://json-schema.org/draft-07/schema#"}},{"name":"cart-list","description":"get products in cart","inputSchema":{"type":"object","properties":{},"additionalProperties":false,"$schema":"http://json-schema.org/draft-07/schema#"}},{"name":"cart-add","description":"Adding products to cart","inputSchema":{"type":"object","properties":{"title":{"type":"string"}},"additionalProperties":false,"$schema":"http://json-schema.org/draft-07/schema#"}},{"name":"add","inputSchema":{"type":"object","properties":{"a":{"type":"number"},"b":{"type":"number"}},"required":["a","b"],"additionalProperties":false,"$schema":"http://json-schema.org/draft-07/schema#"}}]},"jsonrpc":"2.0","id":1}As a recommendation, I prefer to use the Inspector tool as it provides a better experience and is easier to use. The curl command is more of a low-level approach and could be nice to use to get an initial session ID. It does tell you how the underlying protocol works, which can be helpful for debugging.
Summary
Section titled “Summary”In this chapter, we learned about SSE and how to build a server using it.
We also learned about the differences between STDIO and SSE when it comes to testing tools and how to use the Inspector tool with SSE. The difference is that STDIO listens to stdin and stdout while SSE listens to HTTP requests. SSE can also be used to stream responses from LLMs.
Finally, we built our own SSE server and tested it using the Inspector tool and cURL.
In the next chapter, we will look into another transport called Streamable HTTP, which is the preferred transport to use when exposing a server via a URL.
Assignment – SSE server
Section titled “Assignment – SSE server”In this assignment, you will build out an SSE server with some features to support the following use cases:
- List products by category
- Add products to cart
- List products in cart
You can use the code provided in this chapter as a starting point.
Solution
Section titled “Solution”You can access the solution at https://github.com/PacktPublishing/Learn-Model-Context-Protocol-with-Python/blob/main/Chapter04/solutions/README.md.
What is the SSE transport used for?
- A: To expose a server via HTTP
- B: To expose a server via STDIO
- C: To enable streaming of responses from LLMs
Which routes are used for SSE?
- A:
/mcp - B:
/sse - C:
/messages
You can access the solution at https://github.com/PacktPublishing/Learn-Model-Context-Protocol-with-Python/blob/main/Chapter04/solutions/solution-quiz.md.
References
Section titled “References”- Lifecycle: https://modelcontextprotocol.info/specification/draft/basic/lifecycle/
- Starlette: https://www.starlette.io/
- Transports: https://modelcontextprotocol.io/docs/concepts/transports