From 399dad586b97e25d11141f7e1aa086d5019fec67 Mon Sep 17 00:00:00 2001 From: Nikhil Pareek Date: Wed, 4 Nov 2026 01:30:45 -0800 Subject: [PATCH 1/3] fix(mcp): require a cancellation-safe MCP SDK floor Require MCP 1.30.0 consistently in package metadata, instrumentation and floor qualification. Replace the insufficient Pydantic workaround and cover cancellation followed by a healthy request using real MCP clients and servers. Co-Authored-By: Claude Code --- python/frameworks/mcp/README.md | 14 +- python/frameworks/mcp/poetry.lock | 243 +++++++++++++++++- python/frameworks/mcp/pyproject.toml | 2 +- .../mcp/tests/constraints-floor.txt | 7 +- .../mcp/tests/local_cancel_server.py | 47 ++++ .../frameworks/mcp/tests/test_readme_route.py | 11 + .../mcp/tests/test_request_cancellation.py | 81 ++++++ python/frameworks/mcp/traceai_mcp/package.py | 2 +- python/tests/test_framework_mcp.py | 5 +- 9 files changed, 385 insertions(+), 27 deletions(-) create mode 100644 python/frameworks/mcp/tests/local_cancel_server.py create mode 100644 python/frameworks/mcp/tests/test_request_cancellation.py diff --git a/python/frameworks/mcp/README.md b/python/frameworks/mcp/README.md index 040e288da..8f1a00c87 100644 --- a/python/frameworks/mcp/README.md +++ b/python/frameworks/mcp/README.md @@ -15,7 +15,7 @@ Native MCP error spans can contain exception text and stack traces. The `FI_HIDE Use Python 3.11–3.13. Install the published package and the MCP 1.x SDK: ```bash -pip install "traceAI-mcp>=0.1.3" "mcp>=1.8.1,<2" +pip install "traceAI-mcp>=0.1.3" "mcp>=1.30.0,<2" ``` Keep your existing application, agent, or model instrumentation to create spans. Configure its provider/exporter in both client and server processes. Enable MCP propagation in each process before importing transport functions: @@ -26,17 +26,11 @@ from traceai_mcp import MCPInstrumentor MCPInstrumentor().instrument() ``` -The instrumentor connects existing spans; installing it alone will not create a request or tool span tree. Its package dependency remains `mcp>=1.8.1` for compatibility with existing applications, but new MCP 2.x setups should use the native route instead. +The instrumentor connects existing spans; installing it alone will not create a request or tool span tree. It requires `mcp>=1.30.0`; new MCP 2.x setups should use the native route instead. -### MCP 1.8.1 dependency compatibility +### Upgrading older MCP 1.x applications -MCP 1.8.1 uses a private Pydantic API that is absent in newer Pydantic releases. If you must stay on MCP 1.8.1, pin its compatible Pydantic dependency: - -```bash -pip install "traceAI-mcp>=0.1.3" "mcp==1.8.1" "pydantic==2.11.10" -``` - -This pin applies only to MCP 1.8.1; do not impose it on newer SDK versions. +Upgrade the MCP SDK to at least 1.30.0 in both client and server environments. MCP 1.8.1 can close the session when a request is cancelled, preventing subsequent requests from completing. Pinning Pydantic resolves an import incompatibility in that older SDK, but does not fix cancellation. SDK versions below 1.30.0 are no longer supported by this instrumentor. ## Instrumentation lifecycle diff --git a/python/frameworks/mcp/poetry.lock b/python/frameworks/mcp/poetry.lock index eb7309ce9..ea2c1011c 100644 --- a/python/frameworks/mcp/poetry.lock +++ b/python/frameworks/mcp/poetry.lock @@ -65,6 +65,120 @@ files = [ {file = "certifi-2024.6.2.tar.gz", hash = "sha256:3cd43f1c6fa7dedc5899d69d3ad0398fd018ad1a17fba83ddaf78aa46c747516"}, ] +[[package]] +name = "cffi" +version = "2.1.1" +description = "Foreign Function Interface for Python calling C code." +optional = false +python-versions = ">=3.10" +groups = ["main"] +markers = "platform_python_implementation != \"PyPy\"" +files = [ + {file = "cffi-2.1.1-cp310-cp310-macosx_10_15_x86_64.whl", hash = "sha256:baed1e86cc735622097354b9d1281406caf42ff42a886d29faa8e8d1630333be"}, + {file = "cffi-2.1.1-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:ca82be1a1d406ecfe1d25dc16cb33488e5a16bf4438c9fb590484ea29d92478b"}, + {file = "cffi-2.1.1-cp310-cp310-manylinux1_i686.manylinux2014_i686.manylinux_2_17_i686.manylinux_2_5_i686.whl", hash = "sha256:42e2f76b9455f5a9a844f770bf3e200ed3da0e15f5df3db9c31fe80b04b3d004"}, + {file = "cffi-2.1.1-cp310-cp310-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:5a59cc1c4442bc3d5c703bf720b51138d0bfc173618807c9ee2490a7541dd3d9"}, + {file = "cffi-2.1.1-cp310-cp310-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:9f8d177621de5cb38ee3e731eda45d421db093ec0739f46a5594babda7987a98"}, + {file = "cffi-2.1.1-cp310-cp310-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:75f80557d1389eddbd0de2681f6a390a0c5338c31ddaa821381c203fc3fd50d9"}, + {file = "cffi-2.1.1-cp310-cp310-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:194cffa889098ced9976c3fc6340305e43f6303657d298da55366907c05c22d6"}, + {file = "cffi-2.1.1-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:5bb4e7ea95dcd6a014a6fef62e62467d67d8e582326443f3d68e71d6320a9fcf"}, + {file = "cffi-2.1.1-cp310-cp310-musllinux_1_2_i686.whl", hash = "sha256:3d22a20b1fb1632cc72c22f95f7b0d2961c3e1c235f245ba4c606c4771035659"}, + {file = "cffi-2.1.1-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:1dea0e4d7d4f11f619fe8c1d76caf49e24405b4b5743c0e3be16a500ecd930c9"}, + {file = "cffi-2.1.1-cp310-cp310-win32.whl", hash = "sha256:7ce713ace7c0e4520535b42b77eaa742c16dab813978064913e5a3cf82973b41"}, + {file = "cffi-2.1.1-cp310-cp310-win_amd64.whl", hash = "sha256:a48d62ab9d6f4f98c983223a547af44be6ca3691074c31cecced6facd3ba2dc1"}, + {file = "cffi-2.1.1-cp311-cp311-macosx_10_15_x86_64.whl", hash = "sha256:c8d2c9fd1f2d16f780d15127abb050d13d1a76c03a4bd87d7e4980e45e511e12"}, + {file = "cffi-2.1.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:398aff33cee2767e3e781d2554c54bd0dff386bb437581e0d8011fde1a942ec1"}, + {file = "cffi-2.1.1-cp311-cp311-manylinux1_i686.manylinux2014_i686.manylinux_2_17_i686.manylinux_2_5_i686.whl", hash = "sha256:154852545011f779917b11c78db2358d095da62a9a172b78ad0a583ee5adc0d0"}, + {file = "cffi-2.1.1-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:3311ed60d36f83378794e1009ac6258bafbf81f7888b4caa7b35a521e3f95813"}, + {file = "cffi-2.1.1-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:6e192623c49c94421616a5778fba35cf0d5a8d000650c1967ef4448ee5cdd990"}, + {file = "cffi-2.1.1-cp311-cp311-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:a6e721d4b0e45d5b65e87534470e67b18dcd092c83f68fba09f152b9cbc061af"}, + {file = "cffi-2.1.1-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:34e261f78cb6ceaaa36f42f2613f4380d94d9c759a9c73c769ee6e0247364632"}, + {file = "cffi-2.1.1-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:7225e4514edb64eb6740324353e0da0711954fd8d7da4576755b1c6e09b697cd"}, + {file = "cffi-2.1.1-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:df913725b79db7bcf03448f36b7bf8815363417d5b58deecf9305e3e30f0f21a"}, + {file = "cffi-2.1.1-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:f5cfbc5fe74540d335175b656c725d74d90e3730c626d92575eea35029d9afaa"}, + {file = "cffi-2.1.1-cp311-cp311-win32.whl", hash = "sha256:f8ec5e643a9a937f64e1999eb9f75d072263751912dc5cd06d3c85f8f44be7c3"}, + {file = "cffi-2.1.1-cp311-cp311-win_amd64.whl", hash = "sha256:42f6930c31dc7f50732c9ae793c2786c7b6b044195967bbdde40bb9be81c4cc0"}, + {file = "cffi-2.1.1-cp311-cp311-win_arm64.whl", hash = "sha256:c7659f22557c5a0bc4855cd635f55edec690cc008a40768527762cb9fb263455"}, + {file = "cffi-2.1.1-cp312-cp312-macosx_10_15_x86_64.whl", hash = "sha256:c8c69575568085ba0b1b10c0249d779a214aea6f6522e949a0fc9fb0fcb449d0"}, + {file = "cffi-2.1.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:f81b3b8f3d4e343550fa4baa0e479bba9f2d29ce9c2e9b51d1ce1718d7442fcf"}, + {file = "cffi-2.1.1-cp312-cp312-manylinux1_i686.manylinux2014_i686.manylinux_2_17_i686.manylinux_2_5_i686.whl", hash = "sha256:811bd1e21d32de12efca32393a0ab3f5133b54fce9bd44b8bd77ab07da14bf6a"}, + {file = "cffi-2.1.1-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:68e62fe11f30d5ca8289242866f0a5291402d8529ca2178ab8afc5c9694ae890"}, + {file = "cffi-2.1.1-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:4a7c934f7360e8cd64fe9efadcbd10c7c6364f531e432b9a4bf5ccbc9e0e8b50"}, + {file = "cffi-2.1.1-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:3143d81e29e1e20a9ce10901ec369012947876596f75a222235965f2b7ae832e"}, + {file = "cffi-2.1.1-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:c1453022f490d2459a11819d83ad1d586e9ff65a12ac3e705ffebd46d3685dcf"}, + {file = "cffi-2.1.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:208f941bb9d18e768138677f0a6d2ce01f590df56043dda1df1535ac57c88517"}, + {file = "cffi-2.1.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:210019b6c7cf07f081b4c54635c8cf744377001350e29cc0f81c4377b4797735"}, + {file = "cffi-2.1.1-cp312-cp312-win32.whl", hash = "sha256:046bfc24911b37851ee1b51aab8bffe713d89c68c6a057b09484ce9fd5f69b4e"}, + {file = "cffi-2.1.1-cp312-cp312-win_amd64.whl", hash = "sha256:f53e442b08449d42821fa4a4fba000095af9f62742a500f978a9f557ec44339a"}, + {file = "cffi-2.1.1-cp312-cp312-win_arm64.whl", hash = "sha256:7bde5e4cc5c10140859842b9d383af292b22639a4dffb725314baf45968cef80"}, + {file = "cffi-2.1.1-cp313-cp313-ios_13_0_arm64_iphoneos.whl", hash = "sha256:b5bdfd1c873d4e093aabc0ca84c4ca6dbc4f752afb5c86f146d9742580c9da2e"}, + {file = "cffi-2.1.1-cp313-cp313-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:31348097ff5bbe827ccc41795d4dd099d9f0625e7def00ee653c137a490c2a6c"}, + {file = "cffi-2.1.1-cp313-cp313-macosx_10_15_x86_64.whl", hash = "sha256:9d2055050ea716bd38b7f7f1579c275386646b4894c155a3e2f3cd62ed41b7c6"}, + {file = "cffi-2.1.1-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:19ee6127ee34de7d83ce3d371ebc5ed91addbdcc39f9ab15ce4eb35a4e534971"}, + {file = "cffi-2.1.1-cp313-cp313-manylinux1_i686.manylinux2014_i686.manylinux_2_17_i686.manylinux_2_5_i686.whl", hash = "sha256:6a8dddef476fab96d066d578fc88526767b836ab5ab21754e1d5bf3879c31c7c"}, + {file = "cffi-2.1.1-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:f16c709686a78c727bbbf059f92b0bf41c6fc60deec706d2dc19f529175a6125"}, + {file = "cffi-2.1.1-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:fcd22650c908d7b7da162bbfaab594a1227a15d1643a98c68b122ac642fa2264"}, + {file = "cffi-2.1.1-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:aa9511c62d14da7aacc9b4bf51f3f697a621e83b2d6919008243c3aad168eea3"}, + {file = "cffi-2.1.1-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:a931079504ecc49efed7744c476a5c343a92fabf66dec2db95edb1b2fdc770e2"}, + {file = "cffi-2.1.1-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:a2d7755bef5a12ed488f4ef1f1b69ee9191d7396083b755a5d2295f6edb4768b"}, + {file = "cffi-2.1.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:e0bcb7e0f677f543555d2adff3bf19c05f66cdb4796e5ff602442ab2fe3c4ef7"}, + {file = "cffi-2.1.1-cp313-cp313-win32.whl", hash = "sha256:334644fbac4eff73d985a17a91226df55d0f394160c4cfb880e084c8f7161cac"}, + {file = "cffi-2.1.1-cp313-cp313-win_amd64.whl", hash = "sha256:1aa5645c30469b09530c4ebca77ebf8f17618293c58f8549cb1a543a50236e7d"}, + {file = "cffi-2.1.1-cp313-cp313-win_arm64.whl", hash = "sha256:63bbfd5ded17c4840ac07cd8f1c21ba9d9708141f840b324f422f41b207e3973"}, + {file = "cffi-2.1.1-cp314-cp314-ios_13_0_arm64_iphoneos.whl", hash = "sha256:7dbb61fe3a7699468030f71bbe5f8a0e326a151daa91beb11a6fc1f980c55e1c"}, + {file = "cffi-2.1.1-cp314-cp314-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:f24fb43132a4c6b4cb4eb029492919b2db645be6808d738f244fd146c03c32cb"}, + {file = "cffi-2.1.1-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:d28630f5854ab07ab1fd4aba756de52326c82e6be15d414b12793f1975048b54"}, + {file = "cffi-2.1.1-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:661c298b4821edebead0c91edd2b00374d67ad7c5a1f7a91d4442633b79d6a72"}, + {file = "cffi-2.1.1-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:58acb8ab8e295e6c5ea12f888cbb13cf21511ef2a3303a23f4325c29d17fe5c1"}, + {file = "cffi-2.1.1-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:456a61fa52d579ebf9df2e9552ead5129855dbaff6c1e5a9b1bc408809bdc062"}, + {file = "cffi-2.1.1-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:a4f00aa42f75d6e4595e8866e748cc1705adc0cddfeb2ca86d0d03993d63ba03"}, + {file = "cffi-2.1.1-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:b0431303acaea1089ad4b3e9ce4e6518193def1118d4073ca848635ee4ea2e96"}, + {file = "cffi-2.1.1-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:64faea20f4e2613363a1a9b9c7dd73058f3ecd00133a511e72ad7c511658f527"}, + {file = "cffi-2.1.1-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:5c58fe613dc5e5336357eff555824a314d8e43282600435c8d1cb6a7a2fedd13"}, + {file = "cffi-2.1.1-cp314-cp314-win32.whl", hash = "sha256:1a18a57b58cfb21fc28d72e876acf10eaed67a1ed96226f92af4df681d571c4c"}, + {file = "cffi-2.1.1-cp314-cp314-win_amd64.whl", hash = "sha256:3222ba5d678f80a030e6afbcc33dc1ae5cb45facabb61cee2c7016b8432fde48"}, + {file = "cffi-2.1.1-cp314-cp314-win_arm64.whl", hash = "sha256:ab36d55f9ed2d067327667c2fea18dda018eb628dd6347aa01dda6cf1f5d3836"}, + {file = "cffi-2.1.1-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:7750c6449dff7864bb9bb27ddfb0267756189201a3afc911d82b3caacd70dfc3"}, + {file = "cffi-2.1.1-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:0beceaabe56af686895136a2de78db54ecd8e4046b236b8fd6d6cb61389e9bf2"}, + {file = "cffi-2.1.1-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:49cbc70e6542d4ccccb936558d1064a8012541e78f821f955cff24e357776c94"}, + {file = "cffi-2.1.1-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:e2d65b31f36619cda3999b78b2aa9632e76b78448e7a56fc4240824200e7c4fc"}, + {file = "cffi-2.1.1-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:28907ab9bfb6aa13184cfc17c6b8e1023c5ab6fd7076d8c20a35e59fe04f8f29"}, + {file = "cffi-2.1.1-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:51b31d1c98274844cfd7838ce00bfc27c7423a4dc00fc0772fc3331c2cc90676"}, + {file = "cffi-2.1.1-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:5e7cecbaadb83884793e05828cee59b210b24583b9c7425d0ba6a754fe22eb4e"}, + {file = "cffi-2.1.1-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:25792eac27877609e7bb06d42ff88278a6624fff2ba9bbb523c09616b117e80f"}, + {file = "cffi-2.1.1-cp314-cp314t-win32.whl", hash = "sha256:8ef53b2de9bcb9197d31854256575d59dbac0cba72ac627bb291ef5eceb74be4"}, + {file = "cffi-2.1.1-cp314-cp314t-win_amd64.whl", hash = "sha256:616f097f2fe415bc92a247f02e11f634e1f9e9a83d327e3c915c15089c87869e"}, + {file = "cffi-2.1.1-cp314-cp314t-win_arm64.whl", hash = "sha256:ad2c86c495b899d862ea0f4b42891b8713a3bd45dd4105c7fd51c2a72f39f3a5"}, + {file = "cffi-2.1.1-cp315-cp315-ios_13_0_arm64_iphoneos.whl", hash = "sha256:dddad92b554513a31f272570678ba307fb9f618f05e3d4a5eacafff9eae03e1d"}, + {file = "cffi-2.1.1-cp315-cp315-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:da0e573f9f97159390c89d9f1a9e41908b66d408cc5b58d08cf3847d844c531b"}, + {file = "cffi-2.1.1-cp315-cp315-macosx_10_15_x86_64.whl", hash = "sha256:fb92203a88b3d3053034db775110081c49d28be6551923805e039924093761e4"}, + {file = "cffi-2.1.1-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:2ae64be792b8966f2c69538199728b290e34726562896df1e5dc8ffd8d8188e8"}, + {file = "cffi-2.1.1-cp315-cp315-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:507a24c282e0f42f8ed737cf048572cbf580468da5555764a8331735e9c736b6"}, + {file = "cffi-2.1.1-cp315-cp315-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:246fa40ce8645a614ff682e0b70f37134e460eaf93a775e0cbe3cca585a67a80"}, + {file = "cffi-2.1.1-cp315-cp315-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:471cee653ae88de62096552e6d24ccb4a5adb8c8c9f10b5054d0122c15bf2779"}, + {file = "cffi-2.1.1-cp315-cp315-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:aeae0e330c9f6acd681f647d46cefd30c29f93e3392882e792e82080c9691399"}, + {file = "cffi-2.1.1-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:42a494cee34437f05546455144f2b5d9ac09b1face62bcfce597d2e521066688"}, + {file = "cffi-2.1.1-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:cc572dace3f60ef98d7b12ff411d20f5362feb31a0439eab0085bbfd349982d7"}, + {file = "cffi-2.1.1-cp315-cp315-win32.whl", hash = "sha256:4f42141fc14250de6dde5ee7ea4432be017252d91f19c5ad043c084cea629cac"}, + {file = "cffi-2.1.1-cp315-cp315-win_amd64.whl", hash = "sha256:e6e8cff14d6fb0be70a09c0bdc58096f501952d04624ebf867e0e56da2df8960"}, + {file = "cffi-2.1.1-cp315-cp315-win_arm64.whl", hash = "sha256:27350daa11d4f10c540e6e89dada4c54feb7256ad03e9a4dc075ebad7ba360d1"}, + {file = "cffi-2.1.1-cp315-cp315t-macosx_10_15_x86_64.whl", hash = "sha256:c26608d2222fb1e94487e4a387d85f13eb55d5ed725cb25a0c589ac4ee60e7bc"}, + {file = "cffi-2.1.1-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:4be96343e422f2dfcd12ab5c9f5aebe03f82f737c6bffeca6830b3875cb44aab"}, + {file = "cffi-2.1.1-cp315-cp315t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:937c0052c05a31ca1daf18de3158eed4dbfcb9cc107adbea227728d647be701e"}, + {file = "cffi-2.1.1-cp315-cp315t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:df423d40ee8654634421812bc3b196da3f9bd7d32929da813f8394c4348a5358"}, + {file = "cffi-2.1.1-cp315-cp315t-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:a730a083190634c65cca36ba5f489531576ebd79bcd5c8e172130f6453127231"}, + {file = "cffi-2.1.1-cp315-cp315t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:363e05fa78e15116c3c32c210ee36884fd6b9afa6d440e47112c3bd511d64cb6"}, + {file = "cffi-2.1.1-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:770de9db11e84213beec501cfcaa013b019820ca881e03344dea5844f7876d94"}, + {file = "cffi-2.1.1-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:7da0c5eff80f0197f3b3d1232ec5a682a9325f4ae9016a78f5f5ca35f9ced1f5"}, + {file = "cffi-2.1.1-cp315-cp315t-win32.whl", hash = "sha256:06c72bb76605a4b0cd0aad6930b69d4baf7dd5d806cfc409b824191099700e66"}, + {file = "cffi-2.1.1-cp315-cp315t-win_amd64.whl", hash = "sha256:d9c275eaacd24aa73f94ffd6de08fc3f932424d8b6c376f4bed7cde376fe7bc3"}, + {file = "cffi-2.1.1-cp315-cp315t-win_arm64.whl", hash = "sha256:d18e5ac0f2f03f4f518d3e23db0f0cad7faa1da8620e9c09461d443bbf6e6692"}, + {file = "cffi-2.1.1.tar.gz", hash = "sha256:dd31f52ea1086513bb9df30f8fcee9b8918323ae067a3d5b78bc826a000712be"}, +] + +[package.dependencies] +pycparser = {version = "*", markers = "implementation_name != \"PyPy\""} + [[package]] name = "charset-normalizer" version = "3.3.2" @@ -194,6 +308,82 @@ files = [ {file = "colorama-0.4.6.tar.gz", hash = "sha256:08695f5cb7ed6e0531a20572697297273c47b8cae5a63ffc6d6ed5c201be6e44"}, ] +[[package]] +name = "cryptography" +version = "50.0.2" +description = "cryptography is a package which provides cryptographic recipes and primitives to Python developers." +optional = false +python-versions = "!=3.9.0,!=3.9.1,>=3.9" +groups = ["main"] +files = [ + {file = "cryptography-50.0.2-cp311-abi3-macosx_11_0_arm64.whl", hash = "sha256:fa8f5efb344d6908a1ce62f4a24e2e5780f825d6f53f5f50ec5ffacac72936cb"}, + {file = "cryptography-50.0.2-cp311-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:79def8d059362e7831389ed3be0ecdf58a89386e1271e35dd9f5af84e81bffd0"}, + {file = "cryptography-50.0.2-cp311-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:630ebfea3bf689d075f82316324ff7433dc447fe6bc1bfc76524b74b4a9567d2"}, + {file = "cryptography-50.0.2-cp311-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:f9f6143a8c75945eb960d9eb98905a441394abfa24afaae239d514ffb2586480"}, + {file = "cryptography-50.0.2-cp311-abi3-manylinux_2_28_ppc64le.whl", hash = "sha256:a582ab2ae1d34f67112cadc86702774c9ea4374df6bca6afe672817203c99134"}, + {file = "cryptography-50.0.2-cp311-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:4061c0079120205fb760c58acab6443e217307dcf05e3702cf970e0689972856"}, + {file = "cryptography-50.0.2-cp311-abi3-manylinux_2_31_armv7l.whl", hash = "sha256:ac9ed99d81760c62fe89d5f0815cdfa1ba9a35141cf30f1c2d044f04b4803d2e"}, + {file = "cryptography-50.0.2-cp311-abi3-manylinux_2_34_aarch64.whl", hash = "sha256:87e9ce85beb6b328ba370cc6e6aea483c92617b4c95b1d33a49297eb662bfb04"}, + {file = "cryptography-50.0.2-cp311-abi3-manylinux_2_34_ppc64le.whl", hash = "sha256:f265528741e048bce55c3463ed721fb0aa45a5888d8add8cfeccb3035451bbdc"}, + {file = "cryptography-50.0.2-cp311-abi3-manylinux_2_34_x86_64.whl", hash = "sha256:9dab55f57c74c3cad24c323bacbbd04be4705ba6eb0d92e920b1fc4837ed5079"}, + {file = "cryptography-50.0.2-cp311-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:25784ce8b9621c90c643efb9e1e2162ab3b0224cae446ad5e70e7fcb1ce18b51"}, + {file = "cryptography-50.0.2-cp311-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:85d0d9a31b9098e98534226d5686b47264b95e62ce459dc2e62fdfc809f9fe93"}, + {file = "cryptography-50.0.2-cp311-abi3-win_amd64.whl", hash = "sha256:7afa5a6602a9f29af1f3a2965f831bae7c9d5d597b7cbb716d41ab3b7d89879c"}, + {file = "cryptography-50.0.2-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:f785f6161f202ab04d8ca194158968798e480ca058943907972da5f12e2881e8"}, + {file = "cryptography-50.0.2-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:0ecbc5652bdb6fc9eaf89a7d196e20941adfe812f43bc4ca05d9150496821047"}, + {file = "cryptography-50.0.2-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:ab50ee449bf968271e820086f10a33d101dd060370abc10bcd22279be2656539"}, + {file = "cryptography-50.0.2-cp314-cp314t-manylinux_2_28_aarch64.whl", hash = "sha256:a9f7355e6fab51f6c369b86fb7571cffa05edee2c2121e0380a37fb9ac1cd5c1"}, + {file = "cryptography-50.0.2-cp314-cp314t-manylinux_2_28_ppc64le.whl", hash = "sha256:94e5e9f108ee10471288214d3d233fbfbb492840a8457eb85178d643ddeb32c7"}, + {file = "cryptography-50.0.2-cp314-cp314t-manylinux_2_28_x86_64.whl", hash = "sha256:241449bf940a5d27309bd317e6f9a2af6932113818bb2b8f5c59ddc7ef16da18"}, + {file = "cryptography-50.0.2-cp314-cp314t-manylinux_2_31_armv7l.whl", hash = "sha256:d8947001be83df1394050758ce0e745dd74fb134eef0a4b5124208dfc3a68c37"}, + {file = "cryptography-50.0.2-cp314-cp314t-manylinux_2_34_aarch64.whl", hash = "sha256:4a20ce1e5cb4284a86692fdcba7cb8754185c6b2e5c56fcef3751cf451d3cdc2"}, + {file = "cryptography-50.0.2-cp314-cp314t-manylinux_2_34_ppc64le.whl", hash = "sha256:84f964e537f916e2cc85199e5a88742e964939b575ac8598b3f9d6cc416cdaf1"}, + {file = "cryptography-50.0.2-cp314-cp314t-manylinux_2_34_x86_64.whl", hash = "sha256:828d49b0ff5a0e3975865571c5d91dbbdd0d38d8289b249a163e9425413a5e05"}, + {file = "cryptography-50.0.2-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:deb9fde5c60e437ee4821bc9bc39ff31b42135c27e1dc61ef0a629389c1de62e"}, + {file = "cryptography-50.0.2-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:8c71ba2cd31fc93748c38e1b613200ff1c2665cbfd5341fe3a61cfde35a1430e"}, + {file = "cryptography-50.0.2-cp314-cp314t-win_amd64.whl", hash = "sha256:78198641e5be9521beea5aa782bb551a58068d10e6eb04c9c680c1b69f2e7d45"}, + {file = "cryptography-50.0.2-cp315-abi3.abi3t-macosx_11_0_arm64.whl", hash = "sha256:edc3342adf8f697fc5f59c887a304356f147b397809440ed64e2fa6af2f50f37"}, + {file = "cryptography-50.0.2-cp315-abi3.abi3t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:d370b8d1dfcdf7130178137f6fbee6140774a1acc6cacefc4b42643ec11d0a3a"}, + {file = "cryptography-50.0.2-cp315-abi3.abi3t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:f2f9bd7f90c64fe89253f0a2c05e3c4856072660429ce8831b4235bf29403a67"}, + {file = "cryptography-50.0.2-cp315-abi3.abi3t-manylinux_2_28_aarch64.whl", hash = "sha256:e275096ea1e60cc595cda2836fd4a6c725d1125108b868be17f53684d164e2cc"}, + {file = "cryptography-50.0.2-cp315-abi3.abi3t-manylinux_2_28_ppc64le.whl", hash = "sha256:b13478603dcd0a2479ff8e87e2c19a7d525734686fe3c49542472293a204212d"}, + {file = "cryptography-50.0.2-cp315-abi3.abi3t-manylinux_2_28_x86_64.whl", hash = "sha256:58a0c478eeca76fe5e07993c5a0703def34a6dc6a0cda4f5564639b33112ffe7"}, + {file = "cryptography-50.0.2-cp315-abi3.abi3t-manylinux_2_31_armv7l.whl", hash = "sha256:d38cdff612d06fa6a32840d5e1b1f7a27cee4a349aa9085d94a67789d6bfd408"}, + {file = "cryptography-50.0.2-cp315-abi3.abi3t-manylinux_2_34_aarch64.whl", hash = "sha256:fdd28f912fccfec1846a94e2e1e8f9b0012f557f0c46fe4f3eb0d7a87afcf90b"}, + {file = "cryptography-50.0.2-cp315-abi3.abi3t-manylinux_2_34_ppc64le.whl", hash = "sha256:cbc8738fd8526d80f35cb3a40d41f41a2e7030bb3b18b09a6778ef63d291c2fd"}, + {file = "cryptography-50.0.2-cp315-abi3.abi3t-manylinux_2_34_x86_64.whl", hash = "sha256:e105ab60406787da31fccc883fc0f733af1efd78f0136a4599692c4083a73d0c"}, + {file = "cryptography-50.0.2-cp315-abi3.abi3t-musllinux_1_2_aarch64.whl", hash = "sha256:6f8700550aa1474a91e5dc07049c46f98b423b5b1ddd0483e0b51362eeeaf5be"}, + {file = "cryptography-50.0.2-cp315-abi3.abi3t-musllinux_1_2_x86_64.whl", hash = "sha256:c71be1cbfa5cd9a41ee452acf1eccd82b2c05950358b106ec8ceb83411d1a020"}, + {file = "cryptography-50.0.2-cp315-abi3.abi3t-win_amd64.whl", hash = "sha256:c423ab384a46c4dff7217b2ea5ba2e11cffdeab6441acd04cf65a369caf0366c"}, + {file = "cryptography-50.0.2-cp39-abi3-macosx_11_0_arm64.whl", hash = "sha256:0ec5f09541743261e66e291b4a0cbf0fb2997aeaab6d9e9c740b9dba1b58d1c2"}, + {file = "cryptography-50.0.2-cp39-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:c5e67125c7dca78d199ec4e116aa93dbb83494808ecbb8211a2cb09b1bf41dbd"}, + {file = "cryptography-50.0.2-cp39-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:ee247f5c245c9a2fe7c8e2214e295918838e44e00a45a6718451e4004219e767"}, + {file = "cryptography-50.0.2-cp39-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:dfe9763530994147d9af1def057a5b9658b00e8f8fe8743d144d1e0911c2e454"}, + {file = "cryptography-50.0.2-cp39-abi3-manylinux_2_28_ppc64le.whl", hash = "sha256:58ddb5a8e3179d12f19e4ea34d2d32e9d63a4baa142c875c1eb59f41b7243acd"}, + {file = "cryptography-50.0.2-cp39-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:f21e8a22c8605750c7af886bab299a363721264061b4ac0a30efb73cfd58efc5"}, + {file = "cryptography-50.0.2-cp39-abi3-manylinux_2_31_armv7l.whl", hash = "sha256:9c8402a82ea0dc4ceeab793db05f0fafa8ca139ca34fcde5df0f596103c74107"}, + {file = "cryptography-50.0.2-cp39-abi3-manylinux_2_34_aarch64.whl", hash = "sha256:0ddc924c04591c2811ca024d62ecad4f7f6f08af8939c211438f48a16bd23602"}, + {file = "cryptography-50.0.2-cp39-abi3-manylinux_2_34_ppc64le.whl", hash = "sha256:a6557e5f38e065ca9fbdaf7cfc7435ecb1d113aa81a022d1b51921ee7432e227"}, + {file = "cryptography-50.0.2-cp39-abi3-manylinux_2_34_x86_64.whl", hash = "sha256:1981f1db4630889b9ef7803fadef12b056f428cb6b85c27ba57b774793b6093c"}, + {file = "cryptography-50.0.2-cp39-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:7a8701d6b584d76e909e3d305b7d126b41439876a5aaf76cddc67fc230eafa2e"}, + {file = "cryptography-50.0.2-cp39-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:ce47f66801c20ec6c6632453bb5960fe38939e9306970b48b3a5a26de7745d94"}, + {file = "cryptography-50.0.2-cp39-abi3-win_amd64.whl", hash = "sha256:4e81d95e5bafc2d6e34e4bed780e53e4d5b9a2f928573428aa4d35fbec1eb0de"}, + {file = "cryptography-50.0.2-pp311-pypy311_pp73-manylinux_2_28_aarch64.whl", hash = "sha256:92e665960f25fcdc73725b9cec7a3824f279ba97a98653afe9ffac2e43668f67"}, + {file = "cryptography-50.0.2-pp311-pypy311_pp73-manylinux_2_28_x86_64.whl", hash = "sha256:eef4c2f3423810b3070ab391f85436d2f8bbfcb286ac15cbc73190b3563b1f1a"}, + {file = "cryptography-50.0.2-pp311-pypy311_pp73-manylinux_2_34_aarch64.whl", hash = "sha256:7c6d0330c472d96f6a6afe24d80dfdf15176c33096f0a4397ae4c60f3dd3be48"}, + {file = "cryptography-50.0.2-pp311-pypy311_pp73-manylinux_2_34_x86_64.whl", hash = "sha256:1ba34f04897fcdaa73f74145c25f3ec146fbd56593853e88adc2e811303c5f42"}, + {file = "cryptography-50.0.2-pp311-pypy311_pp80-macosx_11_0_arm64.whl", hash = "sha256:3dc4fd8058cea1644971207d530e1a03a184a805ffc8ebdddf0599d78a331b81"}, + {file = "cryptography-50.0.2-pp311-pypy311_pp80-win_amd64.whl", hash = "sha256:7b75de3c8b3be1cdb1052747c929440c3eea46c1bc2cb8a6e3a48388e9b7b452"}, + {file = "cryptography-50.0.2.tar.gz", hash = "sha256:7b46165bb56eb4704e2eaaf86f3c940d19154535d9b0ca7d6d590b04060e00d5"}, +] + +[package.dependencies] +cffi = {version = ">=2.0.0", markers = "platform_python_implementation != \"PyPy\""} +typing-extensions = {version = ">=4.13.2", markers = "python_full_version < \"3.11.0\""} + +[package.extras] +ssh = ["bcrypt (>=3.1.5)"] + [[package]] name = "exceptiongroup" version = "1.3.0" @@ -404,28 +594,31 @@ referencing = ">=0.31.0" [[package]] name = "mcp" -version = "1.12.3" +version = "1.30.0" description = "Model Context Protocol SDK" optional = false python-versions = ">=3.10" groups = ["main"] files = [ - {file = "mcp-1.12.3-py3-none-any.whl", hash = "sha256:5483345bf39033b858920a5b6348a303acacf45b23936972160ff152107b850e"}, - {file = "mcp-1.12.3.tar.gz", hash = "sha256:ab2e05f5e5c13e1dc90a4a9ef23ac500a6121362a564447855ef0ab643a99fed"}, + {file = "mcp-1.30.0-py3-none-any.whl", hash = "sha256:666edb5009503e1047c9d60346a756f94b261f05cc2625f23d41c728ffc484d0"}, + {file = "mcp-1.30.0.tar.gz", hash = "sha256:445414625fce5c295faa505bb11bacece661ab6f4028d57c935db57820b7a3e4"}, ] [package.dependencies] anyio = ">=4.5" -httpx = ">=0.27" +httpx = ">=0.27.1,<1.0.0" httpx-sse = ">=0.4" jsonschema = ">=4.20.0" -pydantic = ">=2.8.0,<3.0.0" +pydantic = {version = ">=2.11.0,<3.0.0", markers = "python_version < \"3.14\""} pydantic-settings = ">=2.5.2" +pyjwt = {version = ">=2.10.1", extras = ["crypto"]} python-multipart = ">=0.0.9" -pywin32 = {version = ">=310", markers = "sys_platform == \"win32\""} +pywin32 = {version = ">=310", markers = "sys_platform == \"win32\" and python_version < \"3.14\""} sse-starlette = ">=1.6.1" -starlette = ">=0.27" -uvicorn = {version = ">=0.23.1", markers = "sys_platform != \"emscripten\""} +starlette = {version = ">=0.27", markers = "python_version < \"3.14\""} +typing-extensions = ">=4.9.0" +typing-inspection = ">=0.4.1" +uvicorn = {version = ">=0.31.1", markers = "sys_platform != \"emscripten\""} [package.extras] cli = ["python-dotenv (>=1.0.0)", "typer (>=0.16.0)"] @@ -581,6 +774,19 @@ files = [ {file = "protobuf-6.31.1.tar.gz", hash = "sha256:d8cac4c982f0b957a4dc73a80e2ea24fab08e679c0de9deb835f4a12d69aca9a"}, ] +[[package]] +name = "pycparser" +version = "3.11" +description = "C parser in Python" +optional = false +python-versions = ">=3.10" +groups = ["main"] +markers = "platform_python_implementation != \"PyPy\" and implementation_name != \"PyPy\"" +files = [ + {file = "pycparser-3.11-py3-none-any.whl", hash = "sha256:51d5a8ba2be0bbe440b99d2112604c95bbbc3c2748a64260186c541e1729cd80"}, + {file = "pycparser-3.11.tar.gz", hash = "sha256:d875f09c3507d00e1aba0eecc6dcadc1352f30fff09dc6bff2f1c2935e97c2bc"}, +] + [[package]] name = "pydantic" version = "2.11.7" @@ -739,6 +945,25 @@ gcp-secret-manager = ["google-cloud-secret-manager (>=2.23.1)"] toml = ["tomli (>=2.0.1)"] yaml = ["pyyaml (>=6.0.1)"] +[[package]] +name = "pyjwt" +version = "2.15.1" +description = "JSON Web Token implementation in Python" +optional = false +python-versions = ">=3.9" +groups = ["main"] +files = [ + {file = "pyjwt-2.15.1-py3-none-any.whl", hash = "sha256:42d59d631f7768a1028a64c7ff581a9bf7519804daf91fc5b6c56e30eec5e193"}, + {file = "pyjwt-2.15.1.tar.gz", hash = "sha256:4f259e80cdfb6b3fc18a7de51fd1ef9ec79652f25019bae68975ca2468a34df8"}, +] + +[package.dependencies] +cryptography = {version = ">=3.4.0", optional = true, markers = "extra == \"crypto\""} +typing_extensions = {version = ">=4.0", markers = "python_version < \"3.11\""} + +[package.extras] +crypto = ["cryptography (>=3.4.0)"] + [[package]] name = "python-dotenv" version = "1.1.1" @@ -1220,4 +1445,4 @@ type = ["pytest-mypy"] [metadata] lock-version = "2.1" python-versions = ">3.10, <3.14" -content-hash = "f8fe99ba3092627e78d4d2b83a7503f04070e7645ff05f962ef2ed07abda7c72" +content-hash = "4f292e3a2ede4807bb01c566daf947e4b799806ca2eaab1390880a09b4f9d465" diff --git a/python/frameworks/mcp/pyproject.toml b/python/frameworks/mcp/pyproject.toml index 373807d24..5e3e3b0ba 100644 --- a/python/frameworks/mcp/pyproject.toml +++ b/python/frameworks/mcp/pyproject.toml @@ -29,7 +29,7 @@ classifiers = [ [tool.poetry.dependencies] python = ">3.10, <3.14" fi-instrumentation-otel = ">=0.1.11" -mcp = ">=1.8.1" +mcp = ">=1.30.0" [tool.poetry.urls] diff --git a/python/frameworks/mcp/tests/constraints-floor.txt b/python/frameworks/mcp/tests/constraints-floor.txt index 7f6810e88..86b9cda64 100644 --- a/python/frameworks/mcp/tests/constraints-floor.txt +++ b/python/frameworks/mcp/tests/constraints-floor.txt @@ -1,4 +1,3 @@ -# MCP 1.8.1 imports a private Pydantic API removed in newer releases. -# This is a tested floor matrix cell, not a package-wide runtime constraint. -mcp==1.8.1 -pydantic==2.11.10 +# Minimum supported MCP SDK, including request-cancellation liveness. +# Do not pin Pydantic to mask incompatibilities in older, unsupported SDKs. +mcp==1.30.0 diff --git a/python/frameworks/mcp/tests/local_cancel_server.py b/python/frameworks/mcp/tests/local_cancel_server.py new file mode 100644 index 000000000..ee82eba49 --- /dev/null +++ b/python/frameworks/mcp/tests/local_cancel_server.py @@ -0,0 +1,47 @@ +"""Real MCP server for the cancellation-followed-by-healthy-request regression.""" +import asyncio +from importlib.metadata import version +import json +from pathlib import Path +import sys + +from traceai_mcp import MCPInstrumentor + + +def main(): + markers = Path(sys.argv[1]) + if sys.argv[2] == "instrumented": + instrumentor = MCPInstrumentor() + instrumentor.instrument() + assert instrumentor.is_instrumented_by_opentelemetry + + native = int(version("mcp").split(".")[0]) >= 2 + if native: + from mcp.server.mcpserver import MCPServer as Server + else: + from mcp.server.fastmcp import FastMCP as Server + + server = Server("cancellation-regression") + + @server.tool() + async def hold() -> str: + # MCP 1.x requires an explicit protocol cancellation; MCP 2.x sends it + # when the client's call task is cancelled. + request_id = None if native else server.get_context().request_context.request_id + (markers / "started.json").write_text(json.dumps({"id": request_id})) + try: + await asyncio.sleep(60) + except asyncio.CancelledError: + (markers / "cancelled").touch() + raise + return "unexpected completion" + + @server.tool() + async def echo() -> str: + return "healthy" + + server.run(transport="stdio") + + +if __name__ == "__main__": + main() diff --git a/python/frameworks/mcp/tests/test_readme_route.py b/python/frameworks/mcp/tests/test_readme_route.py index 992fa76c6..233e2c67e 100644 --- a/python/frameworks/mcp/tests/test_readme_route.py +++ b/python/frameworks/mcp/tests/test_readme_route.py @@ -9,3 +9,14 @@ def test_readme_distinguishes_native_spans_from_legacy_propagation(): assert "native OpenTelemetry" in readme assert "Do not enable `MCPInstrumentor`" in readme assert "https://docs.futureagi.com/docs/integrations/traceai/mcp-python" in readme + + +def test_readme_and_floor_constraints_require_cancellation_safe_sdk(): + package = Path(__file__).parents[1] + readme = (package / "README.md").read_text() + assert '"mcp>=1.30.0,<2"' in readme + assert '"mcp==1.8.1"' not in readme + assert '"pydantic==2.11.10"' not in readme + constraints = (package / "tests" / "constraints-floor.txt").read_text() + requirements = [line for line in constraints.splitlines() if line and not line.startswith("#")] + assert requirements == ["mcp==1.30.0"] diff --git a/python/frameworks/mcp/tests/test_request_cancellation.py b/python/frameworks/mcp/tests/test_request_cancellation.py new file mode 100644 index 000000000..c0ad3ed9c --- /dev/null +++ b/python/frameworks/mcp/tests/test_request_cancellation.py @@ -0,0 +1,81 @@ +"""Cancellation must end only its request, not the real MCP transport/session.""" +import asyncio +from importlib.metadata import version +import json +from pathlib import Path +import sys + +import anyio +from mcp import ClientSession, StdioServerParameters +import mcp.client.stdio as stdio +from mcp.types import ( + CancelledNotification, + CancelledNotificationParams, + ClientNotification, +) +import pytest + +from traceai_mcp import MCPInstrumentor + + +@pytest.mark.parametrize("instrumented", [False, True], ids=["upstream", "instrumented"]) +def test_cancelled_request_keeps_session_alive(tmp_path, instrumented): + async def wait_for_marker(name): + with anyio.fail_after(5): + while not (tmp_path / name).exists(): + await asyncio.sleep(0.01) + + async def run(): + instrumentor = MCPInstrumentor() + if instrumented: + instrumentor.instrument() + assert instrumentor.is_instrumented_by_opentelemetry + params = StdioServerParameters( + command=sys.executable, + args=[ + "-I", + str(Path(__file__).with_name("local_cancel_server.py")), + str(tmp_path), + "instrumented" if instrumented else "upstream", + ], + ) + try: + with anyio.fail_after(20): + async with stdio.stdio_client(params) as (read, write): + async with ClientSession(read, write) as session: + await session.initialize() + first = await session.call_tool("echo", {}) + assert first.content[0].text == "healthy" + pending = asyncio.create_task(session.call_tool("hold", {})) + try: + await wait_for_marker("started.json") + if int(version("mcp").split(".")[0]) >= 2: + pending.cancel() + else: + request_id = json.loads((tmp_path / "started.json").read_text())["id"] + await session.send_notification( + ClientNotification( + CancelledNotification( + method="notifications/cancelled", + params=CancelledNotificationParams( + requestId=request_id, + reason="synthetic test cancellation", + ), + ) + ) + ) + # Prove the server handled cancellation, not merely that + # echo beat the notification or the hold finished normally. + await wait_for_marker("cancelled") + with anyio.fail_after(5): + healthy = await session.call_tool("echo", {}) + assert healthy.content[0].text == "healthy" + finally: + if not pending.done(): + pending.cancel() + await asyncio.gather(pending, return_exceptions=True) + finally: + if instrumentor.is_instrumented_by_opentelemetry: + instrumentor.uninstrument() + + asyncio.run(run()) diff --git a/python/frameworks/mcp/traceai_mcp/package.py b/python/frameworks/mcp/traceai_mcp/package.py index 776712fc2..06a477ea9 100644 --- a/python/frameworks/mcp/traceai_mcp/package.py +++ b/python/frameworks/mcp/traceai_mcp/package.py @@ -1 +1 @@ -_instruments = ("mcp >= 1.8.1",) +_instruments = ("mcp >= 1.30.0",) diff --git a/python/tests/test_framework_mcp.py b/python/tests/test_framework_mcp.py index 19c9daf09..540da1aeb 100644 --- a/python/tests/test_framework_mcp.py +++ b/python/tests/test_framework_mcp.py @@ -72,8 +72,9 @@ def test_instrumentation_dependencies(self): metadata_deps = [Requirement(dep) for dep in requires("traceAI-mcp") if Requirement(dep).name == "mcp"] assert len(mcp_deps) == len(metadata_deps) == 1 assert mcp_deps[0].specifier == metadata_deps[0].specifier - assert "1.8.0" not in mcp_deps[0].specifier - assert "1.8.1" in mcp_deps[0].specifier + assert "1.8.1" not in mcp_deps[0].specifier + assert "1.29.0" not in mcp_deps[0].specifier + assert "1.30.0" in mcp_deps[0].specifier def test_instrument_registers_post_import_hooks(self): """Test that instrumentation registers all necessary post-import hooks.""" From 3cc47ad755270b96a3638142ac930254d2167dfb Mon Sep 17 00:00:00 2001 From: Nikhil Pareek Date: Wed, 4 Nov 2026 04:59:28 -0800 Subject: [PATCH 2/3] fix(mcp): restore propagation context on stream teardown Own message context in the consuming Context instead of an async generator that may finalize in another task. Restore it on reader/transport exit and on the next receive, including server incoming-message queues. Preserve proxy identity when entering reader contexts. Cover ordinary async-for breaks, cancellation, explicit and transport-only cleanup, copied contexts, and native MCP session lifecycles with asyncio and Trio regressions. Co-Authored-By: Claude Code --- .../mcp/tests/local_context_server.py | 56 ++++ .../mcp/tests/test_context_ownership.py | 277 ++++++++++++++++++ python/frameworks/mcp/traceai_mcp/__init__.py | 192 +++++++----- python/tests/test_framework_mcp.py | 4 +- 4 files changed, 459 insertions(+), 70 deletions(-) create mode 100644 python/frameworks/mcp/tests/local_context_server.py create mode 100644 python/frameworks/mcp/tests/test_context_ownership.py diff --git a/python/frameworks/mcp/tests/local_context_server.py b/python/frameworks/mcp/tests/local_context_server.py new file mode 100644 index 000000000..dbbd15c0f --- /dev/null +++ b/python/frameworks/mcp/tests/local_context_server.py @@ -0,0 +1,56 @@ +"""Real stdio transport consumer used by the context ownership regressions.""" +import sys + +import anyio +from opentelemetry.sdk.trace import TracerProvider +from opentelemetry.sdk.trace.export import SimpleSpanProcessor +from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter + +from traceai_mcp import MCPInstrumentor + +REMOTE_TRACE = 0x12345678901234567890123456789012 +REMOTE_SPAN = 0x1234567812345678 + + +async def main(reason, close): + exporter = InMemorySpanExporter() + provider = TracerProvider() + provider.add_span_processor(SimpleSpanProcessor(exporter)) + tracer = provider.get_tracer("context-lifecycle") + instrumentor = MCPInstrumentor() + instrumentor.instrument() + import mcp.server.stdio as stdio + + try: + with tracer.start_as_current_span("outer") as outer: + async with stdio.stdio_server() as (reader, writer): + with anyio.CancelScope() as scope: + async for _ in reader: + with tracer.start_as_current_span("request") as request: + assert request.get_span_context().trace_id == REMOTE_TRACE + if reason == "cancel": + scope.cancel() + await anyio.sleep(0) + raise AssertionError("cancellation was not delivered") + break + # Native stdio waits for its output pump on normal exit. + await writer.aclose() + if close == "explicit": + await reader.aclose() + with tracer.start_as_current_span("after_close") as after_close: + assert after_close.get_span_context().trace_id == outer.get_span_context().trace_id + with tracer.start_as_current_span("after_transport") as after: + assert after.get_span_context().trace_id == outer.get_span_context().trace_id + spans = {span.name: span for span in exporter.get_finished_spans()} + assert set(spans) == {"outer", "request", "after_transport"} | ( + {"after_close"} if close == "explicit" else set() + ) # Propagation must not add spans of its own. + assert spans["request"].parent.span_id == REMOTE_SPAN + assert spans["after_transport"].parent.span_id == outer.get_span_context().span_id + finally: + instrumentor.uninstrument() + provider.shutdown() + + +if __name__ == "__main__": + anyio.run(main, *sys.argv[1:]) diff --git a/python/frameworks/mcp/tests/test_context_ownership.py b/python/frameworks/mcp/tests/test_context_ownership.py new file mode 100644 index 000000000..bb0768e4b --- /dev/null +++ b/python/frameworks/mcp/tests/test_context_ownership.py @@ -0,0 +1,277 @@ +"""Stream/transport exit, not async-generator GC, owns propagation cleanup.""" +import json +import subprocess +import sys +from contextlib import asynccontextmanager +from contextvars import copy_context +from pathlib import Path + +import anyio +import pytest +from mcp.shared.message import SessionMessage +from mcp.types import JSONRPCMessage, JSONRPCRequest +from opentelemetry import context, trace +from opentelemetry.sdk.trace import TracerProvider +from opentelemetry.trace import NonRecordingSpan, SpanContext, TraceFlags + +from traceai_mcp import ( + ContextAttachingStreamReader, + InstrumentedStreamReader, + ItemWithContext, + MCPInstrumentor, +) + +REMOTE_TRACE = 0x12345678901234567890123456789012 +REMOTE_SPAN = 0x1234567812345678 +REMOTE_CONTEXT = trace.set_span_in_context( + NonRecordingSpan(SpanContext(REMOTE_TRACE, REMOTE_SPAN, True, TraceFlags(1))) +) +TRACEPARENT = f"00-{REMOTE_TRACE:032x}-{REMOTE_SPAN:016x}-01" + + +@pytest.fixture(params=["asyncio", "trio"]) +def backend(request): + if request.param == "trio": + pytest.importorskip("trio") + return request.param + + +def message(reader_type): + if reader_type is ContextAttachingStreamReader: + return ItemWithContext("request", REMOTE_CONTEXT) + request = JSONRPCRequest( + jsonrpc="2.0", id=1, method="ping", params={"_meta": {"traceparent": TRACEPARENT}} + ) + try: + wrapped = JSONRPCMessage(root=request) + except TypeError: # MCP 2.x uses a union rather than a root model. + wrapped = request + return SessionMessage(wrapped) + + +@pytest.mark.parametrize("reason", ["break", "cancel"]) +@pytest.mark.parametrize("close", ["explicit", "transport"]) +def test_real_stdio_transport_restores_parent(reason, close): + request = { + "jsonrpc": "2.0", "id": 1, "method": "initialize", + "params": { + "protocolVersion": "2025-03-26", "capabilities": {}, + "clientInfo": {"name": "context-test", "version": "1"}, + "_meta": {"traceparent": TRACEPARENT}, + }, + } + result = subprocess.run( + [sys.executable, "-I", str(Path(__file__).with_name("local_context_server.py")), reason, close], + input=json.dumps(request) + "\n", text=True, capture_output=True, timeout=15, + ) + assert result.returncode == 0, result.stderr + assert "Failed to detach context" not in result.stderr + + +@pytest.mark.parametrize("reader_type", [InstrumentedStreamReader, ContextAttachingStreamReader]) +@pytest.mark.parametrize("reason", ["break", "cancel"]) +@pytest.mark.parametrize("close", ["aclose", "close", "context"]) +def test_reader_exit_restores_parent(reader_type, reason, close, caplog, backend): + async def run(): + tracer = TracerProvider().get_tracer("reader-lifecycle") + send, receive = anyio.create_memory_object_stream(1) + reader = reader_type(receive) + await send.send(message(reader_type)) + with tracer.start_as_current_span("outer") as outer: + async def consume(stream): + with anyio.CancelScope() as scope: + async for _ in stream: + assert trace.get_current_span().get_span_context().trace_id == REMOTE_TRACE + if reason == "cancel": + scope.cancel() + await anyio.sleep(0) + raise AssertionError("cancellation was not delivered") + break + + if close == "context": + async with reader as stream: + await consume(stream) + else: + await consume(reader) + if close == "aclose": + await reader.aclose() + else: + reader.close() + with tracer.start_as_current_span("independent") as independent: + assert independent.get_span_context().trace_id == outer.get_span_context().trace_id + assert independent.parent.span_id == outer.get_span_context().span_id + # Repeated cleanup must neither detach twice nor overwrite later work. + with tracer.start_as_current_span("later") as later: + await reader.aclose() + assert trace.get_current_span() is later + await send.aclose() + anyio.run(run, backend=backend) + assert "Failed to detach context" not in caplog.text + + +@pytest.mark.parametrize("reader_type", [InstrumentedStreamReader, ContextAttachingStreamReader]) +def test_other_task_close_does_not_steal_context_cleanup(reader_type, caplog, backend): + async def run(): + send, receive = anyio.create_memory_object_stream(1) + reader = reader_type(receive) + await send.send(message(reader_type)) + original = context.get_current() + async for _ in reader: + assert trace.get_current_span().get_span_context().trace_id == REMOTE_TRACE + break + # Task groups inherit context, but ContextVar tokens still belong to + # the consuming task. A child closing the native stream cannot reset them. + async with anyio.create_task_group() as group: + group.start_soon(reader.aclose) + assert trace.get_current_span().get_span_context().trace_id == REMOTE_TRACE + await reader.aclose() + assert context.get_current() is original + await send.aclose() + anyio.run(run, backend=backend) + assert "Failed to detach context" not in caplog.text + + +@pytest.mark.parametrize("reader_type", [InstrumentedStreamReader, ContextAttachingStreamReader]) +def test_next_receive_cancellation_and_explicit_iterator_close(reader_type, caplog, backend): + async def run(): + send, receive = anyio.create_memory_object_stream(2) + reader = reader_type(receive) + await send.send(message(reader_type)) + original = context.get_current() + iterator = reader.__aiter__() + await anext(iterator) + assert trace.get_current_span().get_span_context().trace_id == REMOTE_TRACE + # The next receive restores the previous item before waiting. Its + # cancellation must not leave either remote context or a stale token. + with anyio.move_on_after(0.02) as scope: + await anext(iterator) + assert scope.cancel_called + assert context.get_current() is original + iterator = reader.__aiter__() + await send.send(message(reader_type)) + await anext(iterator) + await iterator.aclose() + assert context.get_current() is original + await reader.aclose() + await send.aclose() + anyio.run(run, backend=backend) + assert "Failed to detach context" not in caplog.text + + +@pytest.mark.parametrize("reader_type", [InstrumentedStreamReader, ContextAttachingStreamReader]) +def test_copied_context_cannot_detach_owner_tokens(reader_type, caplog, backend): + async def run(): + send, receive = anyio.create_memory_object_stream(1) + reader = reader_type(receive) + await send.send(message(reader_type)) + original = context.get_current() + async for _ in reader: + break + inherited = copy_context() + stale = copy_context() + inherited.run(reader.close) + assert trace.get_current_span().get_span_context().trace_id == REMOTE_TRACE + reader.close() + assert context.get_current() is original + # The copied Context also cannot reset a token already used by its owner. + stale.run(reader.close) + assert context.get_current() is original + await send.aclose() + anyio.run(run, backend=backend) + assert "Failed to detach context" not in caplog.text + + +@pytest.mark.parametrize("reader_type", [InstrumentedStreamReader, ContextAttachingStreamReader]) +def test_fresh_iterator_restores_previous_message(reader_type, backend): + async def run(): + send, receive = anyio.create_memory_object_stream(2) + reader = reader_type(receive) + await send.send(message(reader_type)) + plain = ValueError("transport exception value without context") + await send.send(plain) + original = context.get_current() + first = reader.__aiter__() + await anext(first) + assert trace.get_current_span().get_span_context().trace_id == REMOTE_TRACE + async for item in reader: + assert item is plain + assert context.get_current() is original + break + await first.aclose() + await reader.aclose() + await send.aclose() + anyio.run(run, backend=backend) + + +@pytest.mark.parametrize("reason", ["break", "cancel"]) +def test_mcp1_server_session_exit_restores_queued_context(reason, caplog, backend): + from mcp.server import Server + from mcp.server.session import ServerSession + + if not hasattr(ServerSession, "incoming_messages"): + pytest.skip("MCP 2.x per-request sessions have no incoming-message queue") + options = {"init_options": Server("context-test").create_initialization_options()} + + async def run(): + instrumentor = MCPInstrumentor() + instrumentor.instrument() + client_send, server_receive = anyio.create_memory_object_stream(1) + server_send, client_receive = anyio.create_memory_object_stream(1) + original = context.get_current() + tracer = TracerProvider().get_tracer("session-lifecycle") + try: + with anyio.fail_after(5), tracer.start_as_current_span("outer") as outer: + async with ServerSession(server_receive, server_send, **options) as session: + async with anyio.create_task_group() as group: + restore = context.attach(REMOTE_CONTEXT) + try: + group.start_soon(session._incoming_message_stream_writer.send, "request") + finally: + context.detach(restore) + with anyio.CancelScope() as scope: + async for item in session.incoming_messages: + assert item == "request" + assert trace.get_current_span().get_span_context().trace_id == REMOTE_TRACE + if reason == "cancel": + scope.cancel() + await anyio.sleep(0) + raise AssertionError("cancellation was not delivered") + break + with tracer.start_as_current_span("after_session") as after: + assert after.get_span_context().trace_id == outer.get_span_context().trace_id + assert after.parent.span_id == outer.get_span_context().span_id + assert context.get_current() is original + finally: + instrumentor.uninstrument() + await client_send.aclose() + await client_receive.aclose() + anyio.run(run, backend=backend) + assert "Failed to detach context" not in caplog.text + + +@pytest.mark.parametrize("arity", [2, 3]) +def test_callback_transport_exit_restores_parent(arity, backend): + async def run(): + send, receive = anyio.create_memory_object_stream(1) + await send.send(message(InstrumentedStreamReader)) + callback = lambda: "synthetic-session" + + @asynccontextmanager + async def transport(): + async with send, receive: + yield (receive, send) if arity == 2 else (receive, send, callback) + + instrumentor = MCPInstrumentor() + instrumentor.instrument() + try: + original = context.get_current() + async with instrumentor._wrap_transport_with_callback(transport, None, (), {}) as streams: + if arity == 3: + assert streams[2] is callback + async for _ in streams[0]: + assert trace.get_current_span().get_span_context().trace_id == REMOTE_TRACE + break + assert context.get_current() is original + finally: + instrumentor.uninstrument() + anyio.run(run, backend=backend) diff --git a/python/frameworks/mcp/traceai_mcp/__init__.py b/python/frameworks/mcp/traceai_mcp/__init__.py index 09bac6031..f4547afc1 100644 --- a/python/frameworks/mcp/traceai_mcp/__init__.py +++ b/python/frameworks/mcp/traceai_mcp/__init__.py @@ -1,4 +1,5 @@ from contextlib import asynccontextmanager +from contextvars import ContextVar, Token from copy import copy from dataclasses import dataclass from typing import Any, AsyncGenerator, Callable, Collection, Tuple, cast @@ -104,19 +105,15 @@ async def _wrap_transport_with_callback( Tuple["InstrumentedStreamReader", "InstrumentedStreamWriter", Any], None ]: async with wrapped(*args, **kwargs) as streams: - if len(streams) == 3: - read_stream, write_stream, get_session_id_callback = streams - yield ( - self._wrap_stream(read_stream, InstrumentedStreamReader), - self._wrap_stream(write_stream, InstrumentedStreamWriter), - get_session_id_callback, - ) - else: - read_stream, write_stream = streams + reader = self._wrap_stream(streams[0], InstrumentedStreamReader) + try: yield ( - self._wrap_stream(read_stream, InstrumentedStreamReader), - self._wrap_stream(write_stream, InstrumentedStreamWriter), + reader, + self._wrap_stream(streams[1], InstrumentedStreamWriter), + *streams[2:], ) + finally: + reader._restore_context() @asynccontextmanager async def _wrap_plain_transport( @@ -125,10 +122,14 @@ async def _wrap_plain_transport( Tuple["InstrumentedStreamReader", "InstrumentedStreamWriter"], None ]: async with wrapped(*args, **kwargs) as (read_stream, write_stream): - yield ( - self._wrap_stream(read_stream, InstrumentedStreamReader), - self._wrap_stream(write_stream, InstrumentedStreamWriter), - ) + reader = self._wrap_stream(read_stream, InstrumentedStreamReader) + try: + yield ( + reader, + self._wrap_stream(write_stream, InstrumentedStreamWriter), + ) + finally: + reader._restore_context() def _base_session_init_wrapper( self, wrapped: Callable[..., None], instance: Any, args: Any, kwargs: Any @@ -159,44 +160,115 @@ def __init__(self, wrapped: Any, state: Any = None) -> None: self._self_state = state if state is not None else _StreamState() -class InstrumentedStreamReader(_SwitchableProxy): - # ObjectProxy missing context manager - https://github.com/GrahamDumpleton/wrapt/issues/73 +# A token from this marker proves ownership of the exact Context, not just +# the task: copied contexts inherit values but cannot reset each other's tokens. +_context_owner: ContextVar[None] = ContextVar("traceai_mcp_context_owner", default=None) + + +class _ContextIterator: + def __init__(self, reader: "_ContextStreamReader", wrapped: Any) -> None: + self._reader = reader + self._wrapped = wrapped + self._key = object() + self._closed = False + + def __aiter__(self) -> "_ContextIterator": + return self + + async def __anext__(self) -> Any: + if self._closed: + raise StopAsyncIteration + # A caller may start a fresh async-for after breaking out of the last + # one. Its previous message is finished even if its iterator was lost. + self._reader._restore_context() + try: + item = await self._wrapped.__anext__() + item, ctx = self._reader._prepare_item(item) + except BaseException: + self._closed = True + raise + if ctx is not None: + self._reader._attach_context(self._key, ctx) + return item + + async def aclose(self) -> None: + self._reader._restore_context(self._key) + self._closed = True + + +class _ContextStreamReader(_SwitchableProxy): + def __init__(self, wrapped: Any, state: Any = None) -> None: + super().__init__(wrapped, state) + self._self_attachment: ContextVar[tuple[object, Token, Token] | None] = ContextVar( + "traceai_mcp_stream_context", default=None + ) + + def _attach_context(self, key: object, ctx: context.Context) -> None: + restore = context.attach(ctx) + owner = _context_owner.set(None) + self._self_attachment.set((key, restore, owner)) + + def _restore_context(self, key: Any = None) -> None: + attachment = self._self_attachment.get() + if attachment is None: + return + iterator_key, restore, owner = attachment + if key is not None and iterator_key is not key: + return + self._self_attachment.set(None) + try: + _context_owner.reset(owner) + except (ValueError, RuntimeError): + # A different Context may close the shared native stream. It + # drops only its inherited bookkeeping; the consuming Context + # still owns its tokens and restores them on its own exit. + return + context.detach(restore) + + def __aiter__(self) -> _ContextIterator: + # Never suspend a generator with context attached: async-generator GC + # may run in a different task, and async-for break does not close it. + return _ContextIterator(self, self.__wrapped__.__aiter__()) + + def _prepare_item(self, item: Any) -> Tuple[Any, Any]: + raise NotImplementedError + async def __aenter__(self) -> Any: - return await self.__wrapped__.__aenter__() + await self.__wrapped__.__aenter__() + return self async def __aexit__(self, exc_type: Any, exc_value: Any, traceback: Any) -> Any: + self._restore_context() return await self.__wrapped__.__aexit__(exc_type, exc_value, traceback) - async def __aiter__(self) -> AsyncGenerator[Any, None]: + def close(self) -> Any: + self._restore_context() + return self.__wrapped__.close() + + async def aclose(self) -> Any: + # Restore synchronously, before a cancellation checkpoint in native IO. + self._restore_context() + return await self.__wrapped__.aclose() + + +class InstrumentedStreamReader(_ContextStreamReader): + def _prepare_item(self, item: Any) -> Tuple[Any, Any]: from mcp.shared.message import SessionMessage from mcp.types import JSONRPCRequest - async for item in self.__wrapped__: - # SDK receive streams carry transport exceptions as values. - if not self._self_state.active or isinstance(item, Exception): - yield item - continue - session_message = cast(SessionMessage, item) - message = session_message.message - # MCP 1.x uses a JSONRPCMessage root model; 2.x stores the - # concrete JSONRPC variant directly. - request = getattr(message, "root", message) - - if not isinstance(request, JSONRPCRequest): - yield item - continue - - if request.params: - meta = request.params.get("_meta") - if meta: - ctx = propagate.extract(meta) - restore = context.attach(ctx) - try: - yield item - continue - finally: - context.detach(restore) - yield item + # SDK receive streams carry transport exceptions as values. + if not self._self_state.active or isinstance(item, Exception): + return item, None + session_message = cast(SessionMessage, item) + message = session_message.message + # MCP 1.x uses a JSONRPCMessage root model; 2.x stores the + # concrete JSONRPC variant directly. + request = getattr(message, "root", message) + if isinstance(request, JSONRPCRequest) and request.params: + meta = request.params.get("_meta") + if meta: + return item, propagate.extract(meta) + return item, None class InstrumentedStreamWriter(_SwitchableProxy): @@ -262,26 +334,10 @@ async def send(self, item: Any) -> Any: return await self.__wrapped__.send(ItemWithContext(item, ctx)) -class ContextAttachingStreamReader(_SwitchableProxy): - async def __aenter__(self) -> Any: - return await self.__wrapped__.__aenter__() - - async def __aexit__(self, exc_type: Any, exc_value: Any, traceback: Any) -> Any: - return await self.__wrapped__.__aexit__(exc_type, exc_value, traceback) - - async def __aiter__(self) -> AsyncGenerator[Any, None]: - async for item in self.__wrapped__: - # Items can cross a lifecycle transition while queued. Always - # unwrap our envelope, but attach only while currently enabled. - if not isinstance(item, ItemWithContext): - yield item - continue - if not self._self_state.active: - yield item.item - continue - item_with_context = item - restore = context.attach(item_with_context.ctx) - try: - yield item_with_context.item - finally: - context.detach(restore) +class ContextAttachingStreamReader(_ContextStreamReader): + def _prepare_item(self, item: Any) -> Tuple[Any, Any]: + # Items can cross a lifecycle transition while queued. Always + # unwrap our envelope, but attach only while currently enabled. + if isinstance(item, ItemWithContext): + return item.item, item.ctx if self._self_state.active else None + return item, None diff --git a/python/tests/test_framework_mcp.py b/python/tests/test_framework_mcp.py index 540da1aeb..52fef06ae 100644 --- a/python/tests/test_framework_mcp.py +++ b/python/tests/test_framework_mcp.py @@ -247,7 +247,7 @@ def test_context_manager_support(self, mock_stream): async def test_context(): async with reader as stream: - assert stream == mock_stream + assert stream is reader mock_stream.__aenter__.assert_called_once() mock_stream.__aexit__.assert_called_once() @@ -350,7 +350,7 @@ def test_context_manager_support(self, mock_stream): async def test_context(): async with reader as stream: - assert stream == mock_stream + assert stream is reader mock_stream.__aenter__.assert_called_once() mock_stream.__aexit__.assert_called_once() From 8d891dfa04d5ac8ef11f0bef7f4c6cc18d8d43bc Mon Sep 17 00:00:00 2001 From: Nikhil Pareek Date: Wed, 4 Nov 2026 05:44:18 -0800 Subject: [PATCH 3/3] fix(mcp): restore owner context after cross-task iterator close Restore the matching iterator attachment before a closed iterator reports EOF, without detaching a newer iterator's context. Cover owner and child-task close, repeated EOF, and stale iterator cleanup for both readers under asyncio and trio. Co-Authored-By: Claude Code --- .../mcp/tests/test_context_ownership.py | 72 +++++++++++++++++++ python/frameworks/mcp/traceai_mcp/__init__.py | 4 ++ 2 files changed, 76 insertions(+) diff --git a/python/frameworks/mcp/tests/test_context_ownership.py b/python/frameworks/mcp/tests/test_context_ownership.py index bb0768e4b..19e38b4ba 100644 --- a/python/frameworks/mcp/tests/test_context_ownership.py +++ b/python/frameworks/mcp/tests/test_context_ownership.py @@ -131,6 +131,78 @@ async def run(): assert "Failed to detach context" not in caplog.text +@pytest.mark.parametrize("reader_type", [InstrumentedStreamReader, ContextAttachingStreamReader]) +@pytest.mark.parametrize("close_task", ["owner", "child"]) +def test_closed_iterator_owner_next_restores_parent(reader_type, close_task, caplog, backend): + async def run(): + tracer = TracerProvider().get_tracer("iterator-lifecycle") + send, receive = anyio.create_memory_object_stream(1) + reader = reader_type(receive) + await send.send(message(reader_type)) + with tracer.start_as_current_span("outer") as outer: + original = context.get_current() + iterator = reader.__aiter__() + try: + await anext(iterator) + assert trace.get_current_span().get_span_context().trace_id == REMOTE_TRACE + if close_task == "child": + async with anyio.create_task_group() as group: + group.start_soon(iterator.aclose) + # A foreign Context cannot reset the owner's tokens. + assert trace.get_current_span().get_span_context().trace_id == REMOTE_TRACE + else: + await iterator.aclose() + assert context.get_current() is original + with pytest.raises(StopAsyncIteration): + await anext(iterator) + # End-of-stream must restore the parent without reader/transport cleanup. + with tracer.start_as_current_span("independent") as independent: + assert independent.get_span_context().trace_id == outer.get_span_context().trace_id + assert independent.parent.span_id == outer.get_span_context().span_id + assert context.get_current() is original + with tracer.start_as_current_span("later") as later: + with pytest.raises(StopAsyncIteration): + await anext(iterator) + assert trace.get_current_span() is later + finally: + await iterator.aclose() + await reader.aclose() + await send.aclose() + anyio.run(run, backend=backend) + assert "Failed to detach context" not in caplog.text + + +@pytest.mark.parametrize("reader_type", [InstrumentedStreamReader, ContextAttachingStreamReader]) +def test_closed_iterator_cannot_detach_new_iterator_context(reader_type, caplog, backend): + async def run(): + send, receive = anyio.create_memory_object_stream(2) + reader = reader_type(receive) + await send.send(message(reader_type)) + await send.send(message(reader_type)) + original = context.get_current() + first = reader.__aiter__() + second = reader.__aiter__() + try: + await anext(first) + async with anyio.create_task_group() as group: + group.start_soon(first.aclose) + await anext(second) + current = context.get_current() + assert trace.get_current_span().get_span_context().trace_id == REMOTE_TRACE + with pytest.raises(StopAsyncIteration): + await anext(first) + assert context.get_current() is current + await first.aclose() + assert context.get_current() is current + await second.aclose() + assert context.get_current() is original + finally: + await reader.aclose() + await send.aclose() + anyio.run(run, backend=backend) + assert "Failed to detach context" not in caplog.text + + @pytest.mark.parametrize("reader_type", [InstrumentedStreamReader, ContextAttachingStreamReader]) def test_next_receive_cancellation_and_explicit_iterator_close(reader_type, caplog, backend): async def run(): diff --git a/python/frameworks/mcp/traceai_mcp/__init__.py b/python/frameworks/mcp/traceai_mcp/__init__.py index f4547afc1..1a8e685e3 100644 --- a/python/frameworks/mcp/traceai_mcp/__init__.py +++ b/python/frameworks/mcp/traceai_mcp/__init__.py @@ -177,6 +177,10 @@ def __aiter__(self) -> "_ContextIterator": async def __anext__(self) -> Any: if self._closed: + # Another Context can close this iterator without restoring the + # owner's tokens. Finish cleanup when the owner observes EOF, + # but do not detach an attachment from a newer iterator. + self._reader._restore_context(self._key) raise StopAsyncIteration # A caller may start a fresh async-for after breaking out of the last # one. Its previous message is finished even if its iterator was lost.