[Python] Streaming MCP tool (FastMCP streamable-http). Providing client with generated pieces...

Discussão em 'Python' iniciado por Stack, Junho 25, 2025.

  1. Stack

    Stack Membro Participativo

    I'm trying to create an MCP server on the basis of streamable-HTTP version of MCP. My tool has to provide client with some pieces of info (primitives, objects, whatever). But I cannot build stream of these objects from server to MCP client.

    This is my minimalistic MCP tool:

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

    @mcp.tool()
    async def number_stream(count: int, delay: int, ctx: Context):
    for i in range(count):
    await ctx.info(f"increment: {i}")
    await asyncio.sleep(delay)
    mcp.run(transport="streamable-http")


    It works fine, it sends log events to client this looks like this as a tcp-flow:

    POST /mcp/ HTTP/1.1
    host: localhost:8000
    connection: keep-alive
    accept: application/json, text/event-stream
    content-type: application/json
    accept-language: *
    sec-fetch-mode: cors
    user-agent: node
    accept-encoding: gzip, deflate
    content-length: 142

    {"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"_meta":{"progressToken":3},"name":"number_stream","arguments":{"count":3,"delay":2}}}
    HTTP/1.1 200 OK
    date: Wed, 25 Jun 2025 09:45:16 GMT
    server: uvicorn
    cache-control: no-cache, no-transform
    connection: keep-alive
    content-type: text/event-stream
    x-accel-buffering: no
    Transfer-Encoding: chunked
    event: message
    data: {"method":"notifications/message","params":{"level":"info","data":"increment: 0"},"jsonrpc":"2.0"}
    event: message
    data: {"method":"notifications/message","params":{"level":"info","data":"increment: 1"},"jsonrpc":"2.0"}
    event: message
    data: {"method":"notifications/message","params":{"level":"info","data":"increment: 2"},"jsonrpc":"2.0"}
    event: message
    data: {"jsonrpc":"2.0","id":3,"result":{"content":[],"isError":false}}


    But I don't see how I could send sequentially generated objects (ints in this case, but imagine that instead of simple ints those are POJOs) in a natural streaming way. OK, I suppose I could serialize objects into json strings one by one and put them into info-message's data field. But it does not look neat and nice. And I don't see any methods for Context class that are intended to make such stream of generated objects from MCP server.

    Continue reading...

Compartilhe esta Página