reattach 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,12 @@
1
+ __pycache__/
2
+ *.py[cod]
3
+ *.egg-info/
4
+ .venv/
5
+ venv/
6
+ dist/
7
+ build/
8
+ .pytest_cache/
9
+ .ruff_cache/
10
+ node_modules/
11
+ coverage/
12
+ .DS_Store
@@ -0,0 +1,17 @@
1
+ # Changelog
2
+
3
+ ## 0.1.0 (2026-11-16)
4
+
5
+ First release.
6
+
7
+ - `Reattach(app)`: ASGI middleware for Streamable HTTP MCP servers. Gives clients a session
8
+ token that carries their handshake, and when the server no longer knows the session
9
+ (restart, redeploy, another replica, idle timeout) replays `initialize` and
10
+ `notifications/initialized` and retries the request, so clients never see
11
+ `404 Session not found`. Signed tokens (`secret` or `REATTACH_SECRET`), per-credential
12
+ mapping, one shared handshake for concurrent requests, GET streams and DELETE handled,
13
+ JSON and SSE replies. No dependencies.
14
+ - `reattach proxy UPSTREAM`: the same as a reverse proxy for MCP servers in any language
15
+ (needs `reattach[proxy]`: httpx and uvicorn). Streams SSE, forwards every path, answers
16
+ `502` while the upstream is down.
17
+ - Tested with the MCP Python SDK 1.x and 2.x.
reattach-0.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Sri Krishna Lingamaneni
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,144 @@
1
+ Metadata-Version: 2.5
2
+ Name: reattach
3
+ Version: 0.1.0
4
+ Summary: Fix MCP 'Session not found' (HTTP 404) after a Streamable HTTP server restarts, redeploys, scales out or times out a session: ASGI middleware and reverse proxy that re-initialize sessions for clients that never do
5
+ Project-URL: Homepage, https://github.com/srikrishnaL/kitforge/tree/main/packages/reattach
6
+ Project-URL: Source, https://github.com/srikrishnaL/kitforge
7
+ Project-URL: Issues, https://github.com/srikrishnaL/kitforge/issues
8
+ Project-URL: Changelog, https://github.com/srikrishnaL/kitforge/blob/main/packages/reattach/CHANGELOG.md
9
+ Author: Sri Krishna Lingamaneni
10
+ License-Expression: MIT
11
+ License-File: LICENSE
12
+ Keywords: 404,agents,asgi,fastmcp,llm,load balancer,mcp,mcp server,mcp-session-id,middleware,model context protocol,reconnect,redeploy,replicas,restart,reverse proxy,session,session not found,sticky sessions,streamable http
13
+ Classifier: Development Status :: 4 - Beta
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3 :: Only
18
+ Classifier: Topic :: Internet :: WWW/HTTP :: HTTP Servers
19
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
20
+ Classifier: Topic :: Software Development :: Libraries
21
+ Requires-Python: >=3.9
22
+ Provides-Extra: proxy
23
+ Requires-Dist: httpx>=0.24; extra == 'proxy'
24
+ Requires-Dist: uvicorn>=0.20; extra == 'proxy'
25
+ Provides-Extra: test
26
+ Requires-Dist: anyio>=4; extra == 'test'
27
+ Requires-Dist: httpx>=0.24; extra == 'test'
28
+ Requires-Dist: mcp>=1.10; (python_version >= '3.10') and extra == 'test'
29
+ Requires-Dist: pytest>=7; extra == 'test'
30
+ Requires-Dist: uvicorn>=0.20; extra == 'test'
31
+ Description-Content-Type: text/markdown
32
+
33
+ # reattach
34
+
35
+ After a Streamable HTTP MCP server restarts, redeploys or times out an idle session, clients
36
+ keep sending the old `Mcp-Session-Id` and get `404 Session not found`. Many clients never
37
+ re-initialize, so every tool call fails until the user reloads or reconnects by hand.
38
+
39
+ reattach fixes it on the server side, for every client at once. Clients get a session id that
40
+ carries their handshake; when the server no longer knows it, reattach replays `initialize`
41
+ and `notifications/initialized` and sends the request on. The client never sees the 404.
42
+
43
+ ## Install
44
+
45
+ ```bash
46
+ pip install reattach # the ASGI middleware, no dependencies
47
+ pip install "reattach[proxy]" # plus the reverse proxy for servers in any language
48
+ ```
49
+
50
+ ## Use
51
+
52
+ Python servers (official MCP SDK, FastMCP, or any ASGI app): wrap the app.
53
+
54
+ ```python
55
+ from mcp.server.fastmcp import FastMCP # SDK 2.x: from mcp.server.mcpserver import MCPServer
56
+ from reattach import Reattach
57
+
58
+ mcp = FastMCP("notes")
59
+
60
+ @mcp.tool()
61
+ def search(q: str):
62
+ """Search the notes."""
63
+ return f"found {q}"
64
+
65
+ app = Reattach(mcp.streamable_http_app()) # run with: uvicorn server:app
66
+ ```
67
+
68
+ Servers in TypeScript, Go or anything else: put the proxy in front.
69
+
70
+ ```bash
71
+ export REATTACH_SECRET="$(openssl rand -hex 32)" # same value on every replica
72
+ reattach proxy http://127.0.0.1:3000 --port 8080
73
+ ```
74
+
75
+ Point clients at `http://<host>:8080/mcp` (every path is forwarded, so OAuth discovery under
76
+ `/.well-known/` keeps working). The proxy can restart the upstream behind it as often as you
77
+ like; while the upstream is down, requests get a `502`, and the first request after it is back
78
+ reattaches.
79
+
80
+ ### Options
81
+
82
+ `Reattach(app, secret=None, *, path=None, max_sessions=10000, on_reattach=None)`
83
+
84
+ - `secret` signs session tokens with HMAC-SHA256. Default: the `REATTACH_SECRET` env var.
85
+ Without one, tokens are unsigned (see Limits). Use the same secret on every replica and
86
+ across deploys, or old tokens stop being recognised (they then pass through as before).
87
+ - `path` handles only that URL path (for example `"/mcp"`); other paths pass through.
88
+ - `max_sessions` caps the in-memory map from tokens to server sessions. The oldest entries
89
+ are dropped first; a dropped token just reattaches on its next request.
90
+ - `on_reattach(token, session_id)` is called after each replayed handshake (logs, metrics).
91
+ The `reattached` attribute counts them.
92
+
93
+ `reattach proxy UPSTREAM` takes `--host` (default 127.0.0.1), `--port` (default 8080),
94
+ `--path`, `--secret`, `--timeout` (upstream read timeout; default none, for SSE streams) and
95
+ `--quiet`.
96
+
97
+ ## How it works
98
+
99
+ 1. On `initialize`, the server's reply is passed through, but its `Mcp-Session-Id` is
100
+ swapped for a token: `ra1.<base64url JSON>.<signature>`. The JSON holds a random 128-bit
101
+ nonce and the client's `protocolVersion`, `capabilities` and `clientInfo` name/version.
102
+ 2. Later requests carry the token. reattach maps it to the server's session id and back on
103
+ the way out.
104
+ 3. If the token is unknown here (restart, other replica) or the server answers `404`
105
+ (expired session), reattach sends `initialize` and `notifications/initialized` from the
106
+ token, with the request's own `Authorization`, and retries the request once on the new
107
+ session. Concurrent requests for the same token share one handshake.
108
+
109
+ Tokens are mapped per credential (`Authorization`, `X-Api-Key`, `Cookie`), so a token used
110
+ with another user's credential gets a new session of its own, never the first user's.
111
+ Session ids that are not reattach tokens, requests without a session id (stateless servers,
112
+ the 2026-07-28 protocol), and every other path pass through untouched. A server that refuses
113
+ the replayed handshake (for example `401` because the token expired) answers the client's
114
+ request itself, so OAuth re-auth still starts normally.
115
+
116
+ ## Limits
117
+
118
+ - State the server kept in memory for the old session is gone: resource subscriptions,
119
+ `logging/setLevel`, in-flight elicitation or sampling requests. Tool calls, resources and
120
+ prompts work as before. If your server keeps no per-session state, `stateless_http=True`
121
+ in the MCP Python SDK avoids sessions altogether and you may not need reattach.
122
+ - A GET stream that was open when the server died ends; the client's reconnect reattaches,
123
+ but events sent in between are lost unless the server has a persistent event store.
124
+ - Without a secret anyone can make a token, which only means they can pick the handshake
125
+ params replayed for their own requests (the same as calling `initialize` themselves). A
126
+ session id is not a credential: authenticate every request as the spec requires.
127
+ - The middleware uses `asyncio` (uvicorn, hypercorn, granian and Starlette all do), not trio.
128
+ - Python 3.9+. Tested with the MCP Python SDK 1.x and 2.x.
129
+
130
+ ## Why this exists
131
+
132
+ Clients that do not recover from `Session not found` are reported again and again, and the
133
+ server owner cannot fix the client:
134
+
135
+ - [anthropics/claude-code#62008](https://github.com/anthropics/claude-code/issues/62008): Claude Code still does not re-initialize after 404 session-not-found
136
+ - [anomalyco/opencode#25137](https://github.com/anomalyco/opencode/issues/25137) and [#37626](https://github.com/anomalyco/opencode/issues/37626): Session not found permanently breaks tool calls
137
+ - [openclaw/openclaw#68187](https://github.com/openclaw/openclaw/issues/68187): sessions stay stale after a server restart
138
+ - [zerodha/kite-mcp-server#83](https://github.com/zerodha/kite-mcp-server/issues/83) and [datagouv/datagouv-mcp#25](https://github.com/datagouv/datagouv-mcp/issues/25): users of hosted servers hitting it
139
+ - [zai-org/feedback#1374](https://github.com/zai-org/feedback/issues/1374): client never re-initializes an expired session after a server restart
140
+
141
+ It also removes the need for sticky sessions behind a load balancer: any replica with the same
142
+ secret can serve any token.
143
+
144
+ Part of [kitforge](https://github.com/srikrishnaL/kitforge). MIT licensed.
@@ -0,0 +1,112 @@
1
+ # reattach
2
+
3
+ After a Streamable HTTP MCP server restarts, redeploys or times out an idle session, clients
4
+ keep sending the old `Mcp-Session-Id` and get `404 Session not found`. Many clients never
5
+ re-initialize, so every tool call fails until the user reloads or reconnects by hand.
6
+
7
+ reattach fixes it on the server side, for every client at once. Clients get a session id that
8
+ carries their handshake; when the server no longer knows it, reattach replays `initialize`
9
+ and `notifications/initialized` and sends the request on. The client never sees the 404.
10
+
11
+ ## Install
12
+
13
+ ```bash
14
+ pip install reattach # the ASGI middleware, no dependencies
15
+ pip install "reattach[proxy]" # plus the reverse proxy for servers in any language
16
+ ```
17
+
18
+ ## Use
19
+
20
+ Python servers (official MCP SDK, FastMCP, or any ASGI app): wrap the app.
21
+
22
+ ```python
23
+ from mcp.server.fastmcp import FastMCP # SDK 2.x: from mcp.server.mcpserver import MCPServer
24
+ from reattach import Reattach
25
+
26
+ mcp = FastMCP("notes")
27
+
28
+ @mcp.tool()
29
+ def search(q: str):
30
+ """Search the notes."""
31
+ return f"found {q}"
32
+
33
+ app = Reattach(mcp.streamable_http_app()) # run with: uvicorn server:app
34
+ ```
35
+
36
+ Servers in TypeScript, Go or anything else: put the proxy in front.
37
+
38
+ ```bash
39
+ export REATTACH_SECRET="$(openssl rand -hex 32)" # same value on every replica
40
+ reattach proxy http://127.0.0.1:3000 --port 8080
41
+ ```
42
+
43
+ Point clients at `http://<host>:8080/mcp` (every path is forwarded, so OAuth discovery under
44
+ `/.well-known/` keeps working). The proxy can restart the upstream behind it as often as you
45
+ like; while the upstream is down, requests get a `502`, and the first request after it is back
46
+ reattaches.
47
+
48
+ ### Options
49
+
50
+ `Reattach(app, secret=None, *, path=None, max_sessions=10000, on_reattach=None)`
51
+
52
+ - `secret` signs session tokens with HMAC-SHA256. Default: the `REATTACH_SECRET` env var.
53
+ Without one, tokens are unsigned (see Limits). Use the same secret on every replica and
54
+ across deploys, or old tokens stop being recognised (they then pass through as before).
55
+ - `path` handles only that URL path (for example `"/mcp"`); other paths pass through.
56
+ - `max_sessions` caps the in-memory map from tokens to server sessions. The oldest entries
57
+ are dropped first; a dropped token just reattaches on its next request.
58
+ - `on_reattach(token, session_id)` is called after each replayed handshake (logs, metrics).
59
+ The `reattached` attribute counts them.
60
+
61
+ `reattach proxy UPSTREAM` takes `--host` (default 127.0.0.1), `--port` (default 8080),
62
+ `--path`, `--secret`, `--timeout` (upstream read timeout; default none, for SSE streams) and
63
+ `--quiet`.
64
+
65
+ ## How it works
66
+
67
+ 1. On `initialize`, the server's reply is passed through, but its `Mcp-Session-Id` is
68
+ swapped for a token: `ra1.<base64url JSON>.<signature>`. The JSON holds a random 128-bit
69
+ nonce and the client's `protocolVersion`, `capabilities` and `clientInfo` name/version.
70
+ 2. Later requests carry the token. reattach maps it to the server's session id and back on
71
+ the way out.
72
+ 3. If the token is unknown here (restart, other replica) or the server answers `404`
73
+ (expired session), reattach sends `initialize` and `notifications/initialized` from the
74
+ token, with the request's own `Authorization`, and retries the request once on the new
75
+ session. Concurrent requests for the same token share one handshake.
76
+
77
+ Tokens are mapped per credential (`Authorization`, `X-Api-Key`, `Cookie`), so a token used
78
+ with another user's credential gets a new session of its own, never the first user's.
79
+ Session ids that are not reattach tokens, requests without a session id (stateless servers,
80
+ the 2026-07-28 protocol), and every other path pass through untouched. A server that refuses
81
+ the replayed handshake (for example `401` because the token expired) answers the client's
82
+ request itself, so OAuth re-auth still starts normally.
83
+
84
+ ## Limits
85
+
86
+ - State the server kept in memory for the old session is gone: resource subscriptions,
87
+ `logging/setLevel`, in-flight elicitation or sampling requests. Tool calls, resources and
88
+ prompts work as before. If your server keeps no per-session state, `stateless_http=True`
89
+ in the MCP Python SDK avoids sessions altogether and you may not need reattach.
90
+ - A GET stream that was open when the server died ends; the client's reconnect reattaches,
91
+ but events sent in between are lost unless the server has a persistent event store.
92
+ - Without a secret anyone can make a token, which only means they can pick the handshake
93
+ params replayed for their own requests (the same as calling `initialize` themselves). A
94
+ session id is not a credential: authenticate every request as the spec requires.
95
+ - The middleware uses `asyncio` (uvicorn, hypercorn, granian and Starlette all do), not trio.
96
+ - Python 3.9+. Tested with the MCP Python SDK 1.x and 2.x.
97
+
98
+ ## Why this exists
99
+
100
+ Clients that do not recover from `Session not found` are reported again and again, and the
101
+ server owner cannot fix the client:
102
+
103
+ - [anthropics/claude-code#62008](https://github.com/anthropics/claude-code/issues/62008): Claude Code still does not re-initialize after 404 session-not-found
104
+ - [anomalyco/opencode#25137](https://github.com/anomalyco/opencode/issues/25137) and [#37626](https://github.com/anomalyco/opencode/issues/37626): Session not found permanently breaks tool calls
105
+ - [openclaw/openclaw#68187](https://github.com/openclaw/openclaw/issues/68187): sessions stay stale after a server restart
106
+ - [zerodha/kite-mcp-server#83](https://github.com/zerodha/kite-mcp-server/issues/83) and [datagouv/datagouv-mcp#25](https://github.com/datagouv/datagouv-mcp/issues/25): users of hosted servers hitting it
107
+ - [zai-org/feedback#1374](https://github.com/zai-org/feedback/issues/1374): client never re-initializes an expired session after a server restart
108
+
109
+ It also removes the need for sticky sessions behind a load balancer: any replica with the same
110
+ secret can serve any token.
111
+
112
+ Part of [kitforge](https://github.com/srikrishnaL/kitforge). MIT licensed.
@@ -0,0 +1,48 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.27"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "reattach"
7
+ version = "0.1.0"
8
+ description = "Fix MCP 'Session not found' (HTTP 404) after a Streamable HTTP server restarts, redeploys, scales out or times out a session: ASGI middleware and reverse proxy that re-initialize sessions for clients that never do"
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ license-files = ["LICENSE"]
12
+ requires-python = ">=3.9"
13
+ authors = [{ name = "Sri Krishna Lingamaneni" }]
14
+ keywords = [
15
+ "mcp", "model context protocol", "mcp server", "streamable http", "session not found",
16
+ "mcp-session-id", "404", "session", "reconnect", "restart", "redeploy", "sticky sessions",
17
+ "load balancer", "replicas", "asgi", "middleware", "reverse proxy", "fastmcp", "llm", "agents",
18
+ ]
19
+ classifiers = [
20
+ "Development Status :: 4 - Beta",
21
+ "Intended Audience :: Developers",
22
+ "Operating System :: OS Independent",
23
+ "Programming Language :: Python :: 3",
24
+ "Programming Language :: Python :: 3 :: Only",
25
+ "Topic :: Internet :: WWW/HTTP :: HTTP Servers",
26
+ "Topic :: Software Development :: Libraries",
27
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
28
+ ]
29
+ dependencies = []
30
+
31
+ [project.optional-dependencies]
32
+ proxy = ["httpx>=0.24", "uvicorn>=0.20"]
33
+ test = ["pytest>=7", "anyio>=4", "httpx>=0.24", "uvicorn>=0.20", "mcp>=1.10; python_version >= '3.10'"]
34
+
35
+ [project.scripts]
36
+ reattach = "reattach.cli:main"
37
+
38
+ [project.urls]
39
+ Homepage = "https://github.com/srikrishnaL/kitforge/tree/main/packages/reattach"
40
+ Source = "https://github.com/srikrishnaL/kitforge"
41
+ Issues = "https://github.com/srikrishnaL/kitforge/issues"
42
+ Changelog = "https://github.com/srikrishnaL/kitforge/blob/main/packages/reattach/CHANGELOG.md"
43
+
44
+ [tool.hatch.build.targets.wheel]
45
+ packages = ["src/reattach"]
46
+
47
+ [tool.pytest.ini_options]
48
+ testpaths = ["tests"]
@@ -0,0 +1,7 @@
1
+ """reattach: MCP Streamable HTTP sessions that survive server restarts, redeploys and timeouts."""
2
+
3
+ from .asgi import Reattach
4
+ from .core import Tokens
5
+
6
+ __version__ = "0.1.0"
7
+ __all__ = ["Reattach", "Tokens", "__version__"]
@@ -0,0 +1,5 @@
1
+ import sys
2
+
3
+ from .cli import main
4
+
5
+ sys.exit(main())