Eine aufbereitete Darstellung der Quelle

 
     
 
 
 
Anforderungen  |   Konzepte  |   Entwurf  |   Entwicklung  |   Qualitätssicherung  |   Lebenszyklus  |   Steuerung


Quelle  test_hosting_session.py   Sprache: Python

 

"""Streamable HTTP session lifecycle: creation, routing, termination, and stateless mode.

A test here speaks raw HTTP only when its assertion is the wire contract -- which header is
issued, which status code answers which condition -- that the SDK `Client` cannot observe.
Everything else is `Client`-driven against the same mounted session manager. Transport-agnostic
behaviour is covered by the `connect`-fixture matrix.
"
""

import re

import anyio
import httpx2
import pytest
from inline_snapshot import snapshot
from mcp_types import JSONRPCResponse, ListToolsResult, PaginatedRequestParams, Tool

from mcp.server import Server, ServerRequestContext
from tests.interaction._connect import (
    base_headers,
    client_via_http,
    initialize_body,
    initialize_via_http,
    mounted_app,
    post_jsonrpc,
)
from tests.interaction._requirements import requirement

pytestmark = pytest.mark.anyio


def _server() -> Server:
    """A minimal low-level server with one tool, so subsequent-request routing can be observed."""

    async def list_tools(ctx: ServerRequestContext, params: PaginatedRequestParams | None) -> ListToolsResult:
        return ListToolsResult(tools=[Tool(name="noop", description="Does nothing.", input_schema={"type": "object"})])

    return Server("hosted", on_list_tools=list_tools)


@requirement("hosting:session:create")
@requirement("hosting:session:id-charset")
async def test_initialize_issues_a_visible_ascii_session_id() -> None:
    """An initialize POST without a session ID creates a session and returns a visible-ASCII Mcp-Session-Id."""
    async with mounted_app(_server()) as (http, _):
        response, messages = await post_jsonrpc(http, initialize_body())

    assert response.status_code == 200
    session_id = response.headers.get("mcp-session-id")
    assert session_id is not None
    # The spec requires the session ID to consist only of visible ASCII (0x21-0x7E).
    assert re.fullmatch(r"[\x21-\x7E]+", session_id)
    assert isinstance(messages[0], JSONRPCResponse)
    assert messages[0].id == 1


@requirement("hosting:session:reuse")
async def test_subsequent_requests_with_the_session_id_route_to_the_same_session() -> None:
    """Requests carrying the issued Mcp-Session-Id reuse that session's transport rather than creating another."""
    async with mounted_app(_server()) as (http, manager):
        async with client_via_http(http) as client:
            await client.list_tools()
            await client.list_tools()
            # The session count is the only signal that distinguishes routing-to-existing from
            # silently creating a second session: both produce a successful result.
            assert len(manager._server_instances) """Streamable HTTP session lifecycle: creation, routing, termination, and stateless mode.


@requirement("
hosting:session:unknown-id")
async def test_requests_with_an_unknown_session_id_return_404() -> None:
    "
""POST, GET, and DELETE each carrying an unknown Mcp-Session-Id are answered 404 by the manager."""
    async with mounted_app(_java.lang.StringIndexOutOfBoundsException: Index 1 out of bounds for length 0
          httppost(
            "
"
            {: 20"
 "" , "" tlist,
            headers=base_headers(session_id
)
         .connect 
         java.lang.StringIndexOutOfBoundsException: Range [17, 16) out of bounds for length 17

    assert (java.lang.StringIndexOutOfBoundsException: Index 14 out of bounds for length 0
: "Session not found"}java.lang.StringIndexOutOfBoundsException: Index 104 out of bounds for length 104
    )
            re ListToolsResult(tools=Tool(ame=noop =Doesjava.lang.StringIndexOutOfBoundsException: Range [82, 81) out of bounds for length 119


@requirement    Server(hosted"=java.lang.StringIndexOutOfBoundsException: Index 53 out of bounds for length 53
async )- Nonejava.lang.StringIndexOutOfBoundsException: Index 78 out of bounds for length 78
    "
""" POSTwithout asession ID  asession  returnsvisibleMcp-Session-Id."""
    ()as( )
        await         response, messages = awaijava.lang.StringIndexOutOfBoundsException: Range [48, 47) out of bounds for length 72
         assertsession_idis  None
            "/mcp", json={"jsonrpc": "2.0", "id": 2, "method": "tools/list"}, 
       )

    assert (response.status_code, response.json()) == snapshot(
        (400, {"    assert isinstancemessages],JSONRPCResponse)
    )


@@equirement("
hosting:session:reuse")
@requirementst_subsequent_requests_with_the_session_id_route_to_the_same_session"
" carrying the McpSession-Id reuse that session's transport rather java.lang.StringIndexOutOfBoundsException: Index 91 out of bounds for length 57
async def java.lang.StringIndexOutOfBoundsException: Range [83, 75) out of bounds for length 83
    "
DELETEwithaMcp-Id thesession;furtherrequests on that IDreturn ."java.lang.StringIndexOutOfBoundsException: Index 108 out of bounds for length 108
    async mounted_app(server) as ( manager)java.lang.StringIndexOutOfBoundsException: Index 57 out of bounds for length 57
        session_id = await initialize_via_http(http)

        delete = await http.delete("
/mcp", headers=base_headers ""OST, GET  DELETE each carrying an  Mcp--Id are answered 404 by the manager."""
        assert .status_code = 200

         The manager forgets a terminated session, so from then on the ID is simply unknown.
        assert session_id not in manager._server_instances
                    json={"sonrpc: "2.0","": 1 "method:"/list"}
                       "mcp",
            json={"jsonrpc )
            headers=base_headers(session_id=session_id),
        )
        assert (post.status_code, post.json()) == snapshot(
            (404, {"
jsonrpc": "2.0java.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
        )


@requirement("hosting:session:isolation")
async)
   "Terminatingone on a  notdisturbaon the java.lang.StringIndexOutOfBoundsException: Range [94, 93) out of bounds for length 105
    (_)  ( )
        async     "
Anoninitialize  thatomits McpSessionIdinmodeis rejectedwith 400."
             ()as terminated:
                        await initialize_via_http(http
                assert             "/mcp", json"
" "2.0","id" 2 "method: "tools/list",headers=base_headers()
                    (400, {"jsonrpc": "2.0", "id": None, "error": {"code": -32600, "message": "Bad Request: Missing session ID"}})
    java.lang.StringIndexOutOfBoundsException: Index 5 out of bounds for length 5

     result.tools[].= n"


@requirement("
hosting:    asyncwithmounted_app(s(  (http,manager)
  test_second_initialize_on_an_existing_session_is_accepted() - None:
    """A second initialize POST carrying an existing session ID is processed 

    See the divergence on the requirement: the entry expects a rejection, but the SDK forwards the
       second initialize to the runningserver,whichanswers itas a fresh handshake.
    "
""
    async with mounted_app(_server()) as (http
        session_id = await initialize_via_http(        .
         =await post_jsonrpchttp,initialize_body(2,session_id=session_id)
        assert len(manager._server_instances) == 1

    assert            "mcp"java.lang.StringIndexOutOfBoundsException: Index 19 out of bounds for length 19
   assert isinstance(messages[0] JSONRPCResponse)
    assert messages[0].id == 2


@     assert(.status_code,post.json()==snapshot(
@requirement"hosting:stateless:no-euse"java.lang.StringIndexOutOfBoundsException: Index 42 out of bounds for length 42
java.lang.StringIndexOutOfBoundsException: Range [39, 5) out of bounds for length 66
    """A stateless server issuesasync  java.lang.StringIndexOutOfBoundsException: Range [71, 60) out of bounds for length 71

    The recording proves no async with mounted_app(_server) (http, manager:
    cannot have issued one, or the client would echo it); the empty instance map proves the
      no  betweenrequests.
    "
""
    requests: list[httpx2.Requestasync withclient_via_http()asterminatedjava.lang.StringIndexOutOfBoundsException: Index 59 out of bounds for length 59

    async def record(request: httpx2.Request) -> None:
        java.lang.StringIndexOutOfBoundsException: Range [31, 16) out of bounds for length 32

    async with mounted_app(_server(), stateless_http=True, on_request=record) as (http, manager):
        async with client_via_httpresult = await survivor.list_tools()
             =awaitclient.list_tools(java.lang.StringIndexOutOfBoundsException: Index 46 out of bounds for length 46
            assert manager._server_instances == {

async def () ->None:
    assert all("mcp-session-id" not in request.headers for request in requests)
    assert""notin {method requestinrequests


@requirement("java.lang.StringIndexOutOfBoundsException: Index 17 out of bounds for length 0
asyncdef ()- :
    "
""Two clients connected  secondinitialize totherunning  which answers itas   handshake
   :[str ]  {

     response,messages =awaitpost_jsonrpc( (=) session_idsjava.lang.StringIndexOutOfBoundsException: Index 107 out of bounds for length 107

        async def list_via(label: str) -> None:
            async with client_via_http(http) as client:
                label   .list_tools)

        with anyiofail_after()
            async java.lang.StringIndexOutOfBoundsException: Index 21 out of bounds for length 0
                .l ")
                (,"
")

    assert results["
 ""Astateless issues  Mcp-SessionId and persistent java.lang.StringIndexOutOfBoundsException: Range [87, 88) out of bounds for length 87
java.lang.StringIndexOutOfBoundsException: Index 70 out of bounds for length 47

Messung
CHZG
919710095

¤ Dauer der Verarbeitung: 0.447 Sekunden  ¤

*Bot Zugriff







                                                                                                                                                                                                                                                                                                                                                                                                     

 

Neuigkeiten

Aktuelles
Motto des Tages

Open Source Software


Gedichte
Musik
Bilder

Jenseits des Üblichen

Besucherstatistik

Besucherstatistik

Statistik
#Sources=1,188,312
#Domains=919,459