mcp-nap 0.2.0__py3-none-any.whl

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,211 @@
1
+ Metadata-Version: 2.5
2
+ Name: mcp-nap
3
+ Version: 0.2.0
4
+ Summary: Keeps stdio MCP servers asleep until a tool is called, so Claude Code, Cursor and VS Code stop holding idle copies.
5
+ Author: Ashutosh Sharma
6
+ License-Expression: MIT
7
+ License-File: LICENSE
8
+ Keywords: claude-code,cursor,mcp,model-context-protocol,vscode
9
+ Classifier: Operating System :: MacOS
10
+ Classifier: Operating System :: Microsoft :: Windows
11
+ Classifier: Operating System :: POSIX :: Linux
12
+ Classifier: Programming Language :: Python :: 3
13
+ Requires-Python: >=3.9
14
+ Description-Content-Type: text/markdown
15
+
16
+ # mcp-nap
17
+
18
+ Your MCP servers sleep until you call a tool.
19
+
20
+ Claude Code, Cursor and VS Code each start their own copies of every stdio MCP server long before anything calls one, and keep them running: Claude Code one set per session, Cursor as soon as a window opens, VS Code one set per chat. mcp-nap stands in for each server, answers the client's startup requests from a cache, and starts the real server only when one of its tools is called. After 10 quiet minutes it stops it again. The model sees the same tool list either way; the saving is the idle node processes and their memory.
21
+
22
+ ```bash
23
+ uv tool install mcp-nap
24
+ mcp-nap wrap # Claude Code
25
+ mcp-nap wrap --client cursor # Cursor
26
+ mcp-nap wrap --client vscode # VS Code
27
+ ```
28
+
29
+ `wrap` rewrites every stdio server in that client's config to run through mcp-nap and prints where it saved a backup first. Name servers to wrap only those: `mcp-nap wrap playwright shadcn`. What to do after `wrap` depends on the client, below. Servers that hold state lose it at the 10-minute stop: Playwright's open browser is the usual one, see [Servers that keep state](#servers-that-keep-state).
30
+
31
+ To try it without installing:
32
+
33
+ ```bash
34
+ uvx mcp-nap wrap
35
+ ```
36
+
37
+ That works, but uvx stays running as the parent of every wrapped server, so each one costs about 56 MB instead of 22 MB. With four servers that is 223 MB per session instead of 89 MB. It also writes `uvx mcp-nap` into the config with no version, so which release runs is up to uv's cache at each start. Install it with `uv tool install` (or `pipx install mcp-nap`) once you keep it.
38
+
39
+ ## Let your agent set it up
40
+
41
+ Paste this to Claude Code, Cursor, VS Code chat or any agent that can run commands on your machine:
42
+
43
+ ```text
44
+ Set up mcp-nap (https://github.com/ashuwhy/mcp-nap) so my stdio MCP servers sleep until a tool is called.
45
+
46
+ 1. If `uv --version` fails, install uv the way https://docs.astral.sh/uv/getting-started/installation/ says. Run `uv tool install mcp-nap`, then `mcp-nap --help`. If mcp-nap is not found, run `uv tool update-shell` and use a new shell.
47
+ 2. Check which of these I use and list the stdio servers (entries with a "command") in each. Read the files only; never print env values or headers, they often hold API keys.
48
+ - Claude Code: `claude` is on PATH; top-level "mcpServers" in ~/.claude.json
49
+ - Cursor: "mcpServers" in ~/.cursor/mcp.json
50
+ - VS Code: "servers" in ~/Library/Application Support/Code/User/mcp.json (macOS), %APPDATA%\Code\User\mcp.json (Windows) or ~/.config/Code/User/mcp.json (Linux)
51
+ 3. Show me the list and ask which to wrap. Flag servers that keep state between calls (Playwright and other browser servers) and suggest --idle 0 for them.
52
+ 4. Wrap with mcp-nap only, never by editing a config yourself:
53
+ Claude Code: mcp-nap wrap NAME...
54
+ Cursor: mcp-nap wrap NAME... --client cursor
55
+ VS Code: mcp-nap wrap NAME... --client vscode
56
+ Wrap the stateful ones in a separate run with --idle 0 added.
57
+ 5. Tell me what each run printed (backup path, any note, the restart step), and that `mcp-nap unwrap` with the same --client undoes it.
58
+ ```
59
+
60
+ ## Clients
61
+
62
+ Checked against Claude Code 2.1, Cursor 3.29 and VS Code 1.146 on macOS. All three change how they run servers often.
63
+
64
+ ### Claude Code
65
+
66
+ Every session starts every stdio server and keeps it until the session ends, so five open sessions hold five idle copies of each. `mcp-nap wrap` edits the user servers in `~/.claude.json` (or `$CLAUDE_CONFIG_DIR/.claude.json`) through `claude mcp`, because live sessions write that file too. Then:
67
+
68
+ > Restart open Claude Code sessions to pick this up.
69
+
70
+ ### Cursor
71
+
72
+ As soon as a signed-in window opens, Cursor starts every enabled server, before any chat, and keeps it until you quit. A second window or workspace can add more copies. `mcp-nap wrap --client cursor` edits `~/.cursor/mcp.json` (`%USERPROFILE%\.cursor\mcp.json` on Windows). Then:
73
+
74
+ > Cursor starts the new command by itself, but copies already running keep the old one: toggle each changed server off and on in Cursor Settings > Tools & MCP, or quit and reopen Cursor.
75
+
76
+ Project `.cursor/mcp.json` files are not touched.
77
+
78
+ ### VS Code
79
+
80
+ Chat in VS Code 1.146 runs on the Copilot agent host, which starts a full set of servers for every chat session and keeps it until you delete the chat or quit. Archiving a chat doesn't stop its set. Opening an empty new chat starts one more, dropped after 5 minutes if you never type. Wrapped, every one of those copies is a sleeping 22 MB wrapper, and the real server runs only around a tool call.
81
+
82
+ `mcp-nap wrap --client vscode` edits the default profile's `mcp.json`: `~/Library/Application Support/Code/User/mcp.json` on macOS, `%APPDATA%\Code\User\mcp.json` on Windows, `~/.config/Code/User/mcp.json` on Linux (or under `$XDG_CONFIG_HOME`). Then:
83
+
84
+ > VS Code picks up the new command in each chat the next time you send a message in it, or quit and reopen VS Code.
85
+
86
+ - A server with `"sandboxEnabled": true` is left alone: the sandbox would not let mcp-nap write its cache.
87
+ - On the older Local harness (`chat.defaultToCopilotHarness` off), VS Code already starts servers on first use, so mcp-nap only adds the idle stop. That harness also needs `rg` (ripgrep) on PATH to start any sandboxed server, wrapped or not; without it the server exits with `ripgrep (rg) not found`.
88
+ - Other profiles, VS Code Insiders and workspace `.vscode/mcp.json` files are not touched.
89
+
90
+ ### Cursor and VS Code config files
91
+
92
+ `wrap` and `unwrap` write the file the way it was laid out (indent, line endings, key order), so `unwrap` gives back the same bytes. A file laid out by hand gets reformatted once, with a note that the backup has it as it was. A file with comments or trailing commas is refused and left as it is, since those would be lost.
93
+
94
+ ### Any other client
95
+
96
+ mcp-nap is a plain stdio server, so any client that runs stdio servers can use it. Put it in front of the server's command:
97
+
98
+ ```json
99
+ "playwright": {
100
+ "command": "mcp-nap",
101
+ "args": ["playwright", "--", "npx", "-y", "@playwright/mcp@latest"]
102
+ }
103
+ ```
104
+
105
+ The first argument names the cache file, so give each server its own. If the client doesn't see your shell's PATH, use the full path that `command -v mcp-nap` prints. (`wrap` already writes the full path.)
106
+
107
+ ## What it saves
108
+
109
+ With four servers, one session held 948 MB bare and 89 MB wrapped.
110
+
111
+ Measured on my laptop with four npx servers (mui, shadcn, playwright, chrome-devtools) per session. A session here is what Claude Code does at startup: spawn every server, initialize, list tools, then sit idle. In Cursor and VS Code, count one session per set of copies the client starts.
112
+
113
+ ```
114
+ machine: Darwin arm64, 16 GB RAM, 6026 MB free at start, Python 3.15.2, node v22.16.0
115
+ uv 0.10.2, uv tool install picked Python 3.13.5
116
+ env: npm_config_prefer_offline=true npm_config_update_notifier=false CHROME_DEVTOOLS_MCP_NO_USAGE_STATISTICS=1 CHROME_DEVTOOLS_MCP_NO_UPDATE_CHECKS=1
117
+ ```
118
+
119
+ Resident memory, 4 servers per session, wrapper cache warm:
120
+
121
+ | sessions | bare | mcp-nap (uv tool install) | mcp-nap (python3 mcp_nap.py) | mcp-nap (uvx) |
122
+ |---|---|---|---|---|
123
+ | 1 | 948 MB (948 MB/session) | 89 MB (89 MB/session) | 75 MB (75 MB/session) | 222 MB (222 MB/session) |
124
+ | 3 | 2635 MB (878 MB/session) | 268 MB (89 MB/session) | 228 MB (76 MB/session) | 668 MB (223 MB/session) |
125
+ | 5 | 3836 MB (767 MB/session) | 447 MB (89 MB/session) | 379 MB (76 MB/session) | 1115 MB (223 MB/session) |
126
+
127
+ - mcp-nap (uv tool install) wrapper: 22.4 MB per wrapped server
128
+ - mcp-nap (python3 mcp_nap.py) wrapper: 19.0 MB per wrapped server
129
+ - mcp-nap (uvx) wrapper: 55.7 MB per wrapped server, uvx stayed as parent in 20 of 20
130
+ - memory pressure at 3 sessions, bare: the compressor grew 486 MB while measuring, so that cell reads up to that much low
131
+ - memory pressure at 5 sessions, bare: the compressor grew 826 MB while measuring, so that cell reads up to that much low
132
+
133
+ Delay, median of 3 runs (nap = python3 mcp_nap.py; cold = no mcp-nap cache yet, asleep = warm cache, server not started):
134
+
135
+ | server | bare start | nap start cold | nap start warm | uv tool start warm | uvx start warm | bare call | nap call asleep |
136
+ |---|---|---|---|---|---|---|---|
137
+ | mui | 515 ms | 517 ms | 34 ms | 33 ms | 73 ms | 6 ms | 541 ms |
138
+ | shadcn | 536 ms | 531 ms | 33 ms | 28 ms | 69 ms | 8 ms | 504 ms |
139
+ | playwright | 523 ms | 532 ms | 34 ms | 29 ms | 72 ms | 927 ms | 1.1 s |
140
+ | chrome-devtools | 593 ms | 600 ms | 33 ms | 28 ms | 68 ms | 12 ms | 568 ms |
141
+
142
+ The bare cells at 3 and 5 sessions were measured while macOS was compressing pages, so they read low and the saving there is larger than shown. The 1-session row had no pressure.
143
+
144
+ The delay is paid on the first call to a server after it went to sleep, then calls run at the bare speed until it idles out. Startup gets faster, because the tool list comes from the cache instead of a fresh node process.
145
+
146
+ To rerun it on your machine (needs uv and node, about 5 minutes):
147
+
148
+ ```bash
149
+ python3 bench/measure.py
150
+ ```
151
+
152
+ It builds the wheel from the checkout, installs it with `uv tool install` into a temp dir, uses its own temp cache, and skips a session count when there isn't free memory for it. `--sessions 1,3` and `--reps 1` make it shorter; `--skip-uv` runs only bare and `python3 mcp_nap.py`.
153
+
154
+ RSS counts shared pages (the node binary, libc) once per process, so every column reads high. Read the difference between columns, not the absolute numbers.
155
+
156
+ ## How it works
157
+
158
+ The first time a wrapped server runs, mcp-nap starts it, passes everything through, and saves its `initialize`, `tools/list`, resource and prompt list replies under `~/.cache/mcp-nap` (`$XDG_CACHE_HOME` if set). After that, a new session gets those replies from the cache and the server stays off. Resource subscriptions and the log level, which Cursor and VS Code send on connect, are taken by mcp-nap and handed to the server when it starts. The first other request, usually a tool call, starts it. It stops again after 10 minutes with nothing in flight.
159
+
160
+ If the server's command or its entry script changes, the cache is refilled on the next start. If the lists change anyway, mcp-nap sends `list_changed` and the client refetches.
161
+
162
+ ## What sleeping costs
163
+
164
+ - The first call after a stop waits for the server to start, about half a second for the npx servers above.
165
+ - No completions while asleep: `completion/complete` gets an empty list until something wakes the server.
166
+ - No resource updates while asleep. Subscriptions are kept and passed on at the next start, but nothing is running to notice a change in between.
167
+ - State the server holds dies at the stop, below.
168
+
169
+ ## Servers that keep state
170
+
171
+ A server that holds state between calls loses it when it stops. Playwright's open browser is the common one. Keep those running for the life of the session with `--idle 0`:
172
+
173
+ ```bash
174
+ mcp-nap unwrap playwright && mcp-nap wrap playwright --idle 0
175
+ ```
176
+
177
+ `--idle N` sets any other timeout in seconds.
178
+
179
+ ## Servers whose login expires
180
+
181
+ Some servers keep an OAuth token that dies on a schedule, and every call then fails with `invalid_grant` until you run the server's own login command. `--reauth ARG` does that for you: on such a failure it runs `<command> ARG`, opens the first https URL it prints, and restarts the server once the login exits cleanly. `wrap` doesn't set it, so add it by hand:
182
+
183
+ ```json
184
+ "google-docs": {
185
+ "command": "mcp-nap",
186
+ "args": ["google-docs", "--reauth", "auth", "--", "google-docs-mcp"]
187
+ }
188
+ ```
189
+
190
+ ## Undo
191
+
192
+ ```bash
193
+ mcp-nap unwrap # or: unwrap --client cursor, unwrap --client vscode
194
+ ```
195
+
196
+ That puts every wrapped server back as it was. Env edits you made to a wrapped entry after `wrap` are kept. Or quit the client and copy the backup back over the config. `wrap` printed its path; it sits next to the config as `.claude.json.mcp-nap-<date>-<time>` or `mcp.json.mcp-nap-<date>-<time>`.
197
+
198
+ ## http and sse servers
199
+
200
+ They are left alone in every client. For Claude Code, mcp-nap edits the config through `claude mcp remove` and `claude mcp add-json`, because live sessions write `~/.claude.json` too, and removing an http or sse server would also delete its OAuth login. Re-adding a server moves it to the end of the list, so if an http server sits between stdio servers, the stdio servers after it end up after it in the file. `wrap` prints a note when that happens. The order doesn't change how Claude Code runs them.
201
+
202
+ ## Limits
203
+
204
+ - macOS, Linux and Windows. The tables above are from macOS. On Linux (a Debian container, node 22, Python 3.11) the tests pass and one `bench/measure.py --sessions 1 --reps 1` run gave 841 MB bare against 42 MB with `uv tool install`.
205
+ - On Windows 11 (arm64, Python 3.9 and 3.13, node 22) the tests pass, and a wrapped `npx` filesystem server starts on the first tool call and leaves no `cmd.exe` or `node.exe` behind after the idle stop, after the session closes, or after the wrapper is killed. Not yet tried there: `wrap` against a real Claude Code install, and Claude Code starting the `mcp-nap` console script. If `claude` is npm's `claude.cmd`, cmd.exe may expand a `%NAME%` inside an env value as `wrap` passes it through.
206
+ - `--client cursor` and `--client vscode` were run against the real apps on macOS only. Their tests pass on Linux and Windows too.
207
+ - Stdio servers only.
208
+ - Without `--client`, `wrap` needs the `claude` CLI on PATH.
209
+ - Without `--client`, `wrap` and `unwrap` pass each server's entry, env values included, to `claude mcp add-json` as a command-line argument. For about a second per server, another user on the same machine can read it in `ps`.
210
+
211
+ MIT licence.
@@ -0,0 +1,6 @@
1
+ mcp_nap.py,sha256=x-FwvClGj6ZR9hT9sJzppYlI9BRd_R1fURgOcopHNWE,29892
2
+ mcp_nap-0.2.0.dist-info/METADATA,sha256=8VIH0CknaoRZga_xiAbKhuT7Sc4stqx7pjjCwaqPu7c,14151
3
+ mcp_nap-0.2.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
4
+ mcp_nap-0.2.0.dist-info/entry_points.txt,sha256=wSfplECvHssmMS0xDzgL-iXq3E4zDuIP-sgPX7cPoMc,41
5
+ mcp_nap-0.2.0.dist-info/licenses/LICENSE,sha256=9bhGPxehakLPYIVW763jqFIl8vPRT-jhCvgY-MKT-Yo,1072
6
+ mcp_nap-0.2.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ mcp-nap = mcp_nap:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Ashutosh Sharma
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.
mcp_nap.py ADDED
@@ -0,0 +1,676 @@
1
+ #!/usr/bin/env python3
2
+ """Stand-in for a stdio MCP server that starts the real one only when a tool is called.
3
+
4
+ mcp-nap <name> [--idle SECONDS] [--reauth ARG] -- <command> [args...]
5
+
6
+ Claude Code starts every configured stdio server with each session, so three open
7
+ sessions meant three copies of a 250 MB node server nobody was calling. This answers
8
+ initialize, tools/list and the resource and prompt lists from a cache written the last
9
+ time the real server ran, takes resource subscriptions and the log level itself and hands
10
+ them to the server when it starts, starts the server on the first other request, and
11
+ stops it after --idle seconds
12
+ (default 600) with nothing in flight; --idle 0 never stops it. The first run has no cache, so it starts the
13
+ server once to fill it.
14
+
15
+ The cache belongs to one command, and a file that command names (the server's entry
16
+ script) being newer means a rebuild or upgrade, so either change starts the server
17
+ at initialize to refill it. A change no named file shows still turns up when the
18
+ server next starts: the new lists replace the cache and the client is sent
19
+ list_changed for each one that differs.
20
+
21
+ With --reauth, a failed tool call whose reply says invalid_grant runs `<command> ARG`
22
+ (the server's own login, e.g. `google-docs-mcp auth`), opens the first https URL it
23
+ prints in the browser, and restarts the server once that login exits cleanly so it
24
+ reads the new token. google-docs needs this because its OAuth app is in Testing
25
+ mode, where Google kills the refresh token 7 days after every login.
26
+ """
27
+
28
+ import glob
29
+ import json
30
+ import os
31
+ import queue
32
+ import re
33
+ import shutil
34
+ import subprocess
35
+ import sys
36
+ import tempfile
37
+ import threading
38
+ import time
39
+
40
+ CACHE_DIR = os.path.join(os.environ.get("XDG_CACHE_HOME") or os.path.expanduser("~/.cache"),
41
+ "mcp-nap")
42
+ INIT_ID = "mcp-nap-init"
43
+ TOOLS_ID = "mcp-nap-tools"
44
+ # Claude Code asks for these right after tools/list when the server declares the capability.
45
+ LISTS = {"resources/list": "resources", "resources/templates/list": "resources",
46
+ "prompts/list": "prompts"}
47
+ # Clients send these on connect (Cursor subscribes, VS Code sets the log level), so a
48
+ # sleeping server answers them itself, as far as its cached capabilities say it can.
49
+ ASLEEP = {"resources/subscribe": ("resources", "subscribe"),
50
+ "resources/unsubscribe": ("resources", "subscribe"),
51
+ "logging/setLevel": ("logging", None), "completion/complete": ("completions", None)}
52
+ REPLAYED = ("logging/setLevel", "resources/subscribe")
53
+ INTERNAL_IDS = (INIT_ID, TOOLS_ID) + tuple("mcp-nap-" + method for method in (*LISTS, *REPLAYED))
54
+ CODE_SUFFIXES = (".js", ".mjs", ".cjs", ".ts", ".py", ".exe")
55
+ __version__ = "0.2.0"
56
+
57
+ LOGIN_URL = re.compile(r"https://\S+")
58
+ LOGIN_NOTE = ("mcp-nap: the OAuth login expired, so the sign-in page is now open in the "
59
+ "browser. Click Allow there, then retry this call.")
60
+
61
+
62
+ class Lazy:
63
+ def __init__(self, name, cmd, idle, reauth):
64
+ self.cache_path = os.path.join(CACHE_DIR, name + ".json")
65
+ self.cmd = cmd
66
+ # Popen on Windows finds npx.exe but not npx.cmd.
67
+ self.argv = [on_path(cmd[0]) or cmd[0]] + cmd[1:]
68
+ self.idle = idle
69
+ self.reauth = reauth
70
+ self.login = None
71
+ self.login_url = None
72
+ self.login_opened = 0.0
73
+ self.child = None
74
+ self.client_init = None
75
+ self.log_level = None
76
+ self.subscribed = {}
77
+ self.in_flight = set()
78
+ self.last_used = time.monotonic()
79
+ self.internal = queue.Queue()
80
+ self.out_lock = threading.Lock()
81
+ self.lock = threading.Lock()
82
+ try:
83
+ with open(self.cache_path) as f:
84
+ self.cache = json.load(f)
85
+ written = os.path.getmtime(self.cache_path)
86
+ except (OSError, ValueError):
87
+ self.cache = None
88
+ # A cache from another command lists another server's tools, one older than a
89
+ # code file the command runs predates the last build or upgrade, and one from 0.1.0
90
+ # has no resource or prompt lists. Other files in argv (--db-path, a log) may be
91
+ # written on every run, and counting them would start the server on every connect.
92
+ if self.cache and (self.cache.get("command") != cmd or "lists" not in self.cache or any(
93
+ is_code(arg) and os.path.getmtime(arg) > written for arg in cmd)):
94
+ self.cache = None
95
+
96
+ def send_client(self, msg):
97
+ line = json.dumps(msg, separators=(",", ":"))
98
+ with self.out_lock:
99
+ sys.stdout.write(line + "\n")
100
+ sys.stdout.flush()
101
+
102
+ def send_child(self, msg):
103
+ self.child.stdin.write(json.dumps(msg, separators=(",", ":")) + "\n")
104
+ self.child.stdin.flush()
105
+
106
+ def await_internal(self, want_id, timeout=60):
107
+ deadline = time.monotonic() + timeout
108
+ while True:
109
+ msg = self.internal.get(timeout=max(0.1, deadline - time.monotonic()))
110
+ if msg.get("id") == want_id:
111
+ return msg
112
+ if msg.get("exited"):
113
+ raise OSError("server exited during startup")
114
+
115
+ def start_child(self):
116
+ # A server stopped for idleness leaves its exit marker behind; drop it.
117
+ while not self.internal.empty():
118
+ self.internal.get_nowait()
119
+ # MCP is UTF-8 whatever the locale; Windows pipes would default to cp1252.
120
+ child = self.child = subprocess.Popen(
121
+ self.argv, stdin=subprocess.PIPE, stdout=subprocess.PIPE, encoding="utf-8", bufsize=1
122
+ )
123
+ threading.Thread(target=self.pump_child, args=(child,), daemon=True).start()
124
+ self.send_child({"jsonrpc": "2.0", "id": INIT_ID, "method": "initialize",
125
+ "params": self.client_init})
126
+ try:
127
+ init = self.await_internal(INIT_ID)
128
+ except (queue.Empty, OSError):
129
+ # A server that exited has already been cleared from self.child by pump_child.
130
+ kill(child)
131
+ self.child = None
132
+ raise
133
+ self.send_child({"jsonrpc": "2.0", "method": "notifications/initialized"})
134
+ declared = init.get("result", {}).get("capabilities", {})
135
+ # What the client asked of the server while it slept, or of an earlier copy.
136
+ if self.log_level and "logging" in declared:
137
+ self.ask_child("logging/setLevel", {"level": self.log_level})
138
+ if (declared.get("resources") or {}).get("subscribe"):
139
+ for uri in self.subscribed:
140
+ self.ask_child("resources/subscribe", {"uri": uri})
141
+ self.send_child({"jsonrpc": "2.0", "id": TOOLS_ID, "method": "tools/list", "params": {}})
142
+ tools = self.await_internal(TOOLS_ID)
143
+ lists = {}
144
+ for method, capability in LISTS.items():
145
+ if capability in declared:
146
+ reply = self.ask_child(method, {})
147
+ lists[method] = {k: reply[k] for k in ("result", "error") if k in reply}
148
+ if "result" in init and "result" in tools:
149
+ served = self.cache
150
+ self.cache = {"command": self.cmd, "initialize": init["result"], "tools": tools["result"],
151
+ "lists": lists}
152
+ os.makedirs(CACHE_DIR, exist_ok=True)
153
+ # The command can carry a token. 0.1.x left this folder 0755.
154
+ os.chmod(CACHE_DIR, 0o700)
155
+ replace_file(self.cache_path, json.dumps(self.cache), 0o600)
156
+ if not served:
157
+ return
158
+ if served["tools"] != self.cache["tools"]:
159
+ self.send_client({"jsonrpc": "2.0", "method": "notifications/tools/list_changed"})
160
+ for capability in sorted({LISTS[m] for m in LISTS
161
+ if served["lists"].get(m) != lists.get(m)}):
162
+ self.send_client({"jsonrpc": "2.0",
163
+ "method": "notifications/%s/list_changed" % capability})
164
+
165
+ def ask_child(self, method, params):
166
+ self.send_child({"jsonrpc": "2.0", "id": "mcp-nap-" + method, "method": method,
167
+ "params": params})
168
+ return self.await_internal("mcp-nap-" + method)
169
+
170
+ def answer_asleep(self, msg, method):
171
+ capability, flag = ASLEEP[method]
172
+ declared = self.cache["initialize"].get("capabilities", {}).get(capability)
173
+ if declared is None or (flag and not declared.get(flag)):
174
+ reply = {"error": {"code": -32601, "message": "Method not found"}}
175
+ elif method == "completion/complete":
176
+ # The cost: no completions until something wakes the server.
177
+ reply = {"result": {"completion": {"values": [], "hasMore": False}}}
178
+ else:
179
+ reply = {"result": {}}
180
+ self.send_client({"jsonrpc": "2.0", "id": msg["id"], **reply})
181
+
182
+ def pump_child(self, child):
183
+ for line in child.stdout:
184
+ try:
185
+ msg = json.loads(line)
186
+ except ValueError:
187
+ continue
188
+ if msg.get("id") in INTERNAL_IDS:
189
+ self.internal.put(msg)
190
+ continue
191
+ if "method" not in msg:
192
+ with self.lock:
193
+ self.in_flight.discard(msg.get("id"))
194
+ self.last_used = time.monotonic()
195
+ # Only failures count: reading a doc that mentions invalid_grant is fine.
196
+ failed = "error" in msg or msg.get("result", {}).get("isError")
197
+ if self.reauth and failed and "invalid_grant" in line:
198
+ self.start_login()
199
+ if "error" in msg:
200
+ msg["error"]["message"] += ". " + LOGIN_NOTE
201
+ else:
202
+ msg["result"].setdefault("content", []).append(
203
+ {"type": "text", "text": LOGIN_NOTE})
204
+ self.send_client(msg)
205
+ self.internal.put({"exited": True})
206
+ # The server died with requests outstanding; fail them rather than hang the session.
207
+ with self.lock:
208
+ orphans, self.in_flight = self.in_flight, set()
209
+ if self.child is child:
210
+ self.child = None
211
+ for rid in orphans:
212
+ self.send_client({"jsonrpc": "2.0", "id": rid,
213
+ "error": {"code": -32603, "message": "MCP server exited"}})
214
+
215
+ def reap_idle(self):
216
+ while True:
217
+ time.sleep(min(15, self.idle))
218
+ with self.lock:
219
+ child = self.child
220
+ quiet = time.monotonic() - self.last_used > self.idle
221
+ if not (child and quiet and not self.in_flight):
222
+ continue
223
+ self.child = None
224
+ self.stop(child)
225
+
226
+ def stop(self, child):
227
+ child.stdin.close()
228
+ try:
229
+ child.wait(5)
230
+ except subprocess.TimeoutExpired:
231
+ kill(child)
232
+
233
+ def start_login(self):
234
+ with self.lock:
235
+ if self.login and self.login.poll() is None:
236
+ # Parallel calls fail together; one tab is enough, but reopen a closed one.
237
+ url = self.login_url
238
+ if not url or time.monotonic() - self.login_opened < 30:
239
+ return
240
+ else:
241
+ url = None
242
+ self.login_url = None
243
+ self.login = subprocess.Popen(
244
+ self.argv + [self.reauth], stdin=subprocess.DEVNULL,
245
+ stdout=subprocess.PIPE, stderr=subprocess.STDOUT, encoding="utf-8",
246
+ errors="replace")
247
+ threading.Thread(target=self.watch_login, args=(self.login,), daemon=True).start()
248
+ if url:
249
+ self.open_login(url)
250
+
251
+ def open_login(self, url):
252
+ self.login_opened = time.monotonic()
253
+ opener = "open" if sys.platform == "darwin" else "xdg-open"
254
+ try:
255
+ if sys.platform == "win32":
256
+ os.startfile(url)
257
+ return
258
+ # stdout is the MCP channel, so the opener must not write to it.
259
+ subprocess.run([opener, url], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
260
+ except OSError:
261
+ pass
262
+
263
+ def watch_login(self, login):
264
+ # Unanswered after 10 minutes: free the callback port so a later failure can retry.
265
+ timer = threading.Timer(600, kill, (login,))
266
+ timer.start()
267
+ for line in login.stdout:
268
+ found = LOGIN_URL.search(line)
269
+ if found and self.login_url is None:
270
+ self.login_url = found.group(0)
271
+ self.open_login(self.login_url)
272
+ timer.cancel()
273
+ if login.wait() != 0:
274
+ return
275
+ # The running server still holds the dead token; the next call starts a fresh one.
276
+ with self.lock:
277
+ child, self.child = self.child, None
278
+ if child:
279
+ self.stop(child)
280
+
281
+ def forward(self, msg):
282
+ with self.lock:
283
+ self.last_used = time.monotonic()
284
+ running = self.child is not None
285
+ if "id" in msg and "method" in msg:
286
+ self.in_flight.add(msg["id"])
287
+ if not running:
288
+ self.start_child()
289
+ self.send_child(msg)
290
+
291
+ def handle(self, msg):
292
+ method = msg.get("method")
293
+ params = msg.get("params") or {}
294
+ if method == "logging/setLevel":
295
+ self.log_level = params.get("level")
296
+ elif method == "resources/subscribe":
297
+ self.subscribed[params.get("uri")] = True
298
+ elif method == "resources/unsubscribe":
299
+ self.subscribed.pop(params.get("uri"), None)
300
+ if method == "initialize":
301
+ self.client_init = msg.get("params", {})
302
+ if self.cache is None:
303
+ self.start_child()
304
+ init = self.cache["initialize"]
305
+ # Claude Code only listens for list_changed from servers that declare it.
306
+ caps = init.setdefault("capabilities", {})
307
+ caps.setdefault("tools", {})["listChanged"] = True
308
+ for capability in ("resources", "prompts"):
309
+ if capability in caps:
310
+ caps[capability]["listChanged"] = True
311
+ self.send_client({"jsonrpc": "2.0", "id": msg["id"], "result": init})
312
+ elif method == "notifications/initialized":
313
+ pass
314
+ elif method == "tools/list" and self.cache is not None:
315
+ self.send_client({"jsonrpc": "2.0", "id": msg["id"], "result": self.cache["tools"]})
316
+ elif (method in LISTS and self.cache is not None and method in self.cache["lists"]
317
+ and "cursor" not in params):
318
+ # A cursor asks for a later page, which only the server has.
319
+ self.send_client({"jsonrpc": "2.0", "id": msg["id"], **self.cache["lists"][method]})
320
+ elif method == "ping":
321
+ self.send_client({"jsonrpc": "2.0", "id": msg["id"], "result": {}})
322
+ elif method in ASLEEP and "id" in msg and self.child is None and self.cache is not None:
323
+ self.answer_asleep(msg, method)
324
+ elif method and method.startswith("notifications/") and self.child is None:
325
+ pass
326
+ elif self.client_init is None:
327
+ # Claude Code 2.1.285 probes with server/discover before initialize. Starting
328
+ # the server now would send it initialize with null params, which it drops
329
+ # without a reply, so answer as an initialize-only server and let the client
330
+ # fall back.
331
+ if "id" in msg:
332
+ self.send_client({"jsonrpc": "2.0", "id": msg["id"],
333
+ "error": {"code": -32601, "message": "Method not found"}})
334
+ else:
335
+ self.forward(msg)
336
+
337
+ def run(self):
338
+ # --idle 0 keeps a server that holds state, such as a browser, running once started.
339
+ if self.idle > 0:
340
+ threading.Thread(target=self.reap_idle, daemon=True).start()
341
+ sys.stdin.reconfigure(encoding="utf-8")
342
+ for line in sys.stdin:
343
+ try:
344
+ msg = json.loads(line)
345
+ except ValueError:
346
+ continue
347
+ try:
348
+ self.handle(msg)
349
+ except (OSError, queue.Empty) as err:
350
+ if "id" in msg and "method" in msg:
351
+ with self.lock:
352
+ self.in_flight.discard(msg["id"])
353
+ self.send_client({"jsonrpc": "2.0", "id": msg["id"], "error": {
354
+ "code": -32603, "message": "could not start MCP server: %s" % err}})
355
+ if self.child:
356
+ kill(self.child)
357
+ if self.login:
358
+ kill(self.login)
359
+
360
+
361
+ def is_code(path):
362
+ return os.path.isfile(path) and (path.endswith(CODE_SUFFIXES) or
363
+ os.name != "nt" and os.access(path, os.X_OK))
364
+
365
+
366
+ def on_path(name):
367
+ if sys.platform != "win32" or os.path.dirname(name):
368
+ return shutil.which(name)
369
+ # shutil.which on Windows looks in the working directory first, and Claude Code
370
+ # starts servers in the project folder, where a cloned repo could plant npx.cmd.
371
+ pathext = [e for e in os.environ.get("PATHEXT", ".COM;.EXE;.BAT;.CMD").lower().split(";") if e]
372
+ exts = [""] if os.path.splitext(name)[1].lower() in pathext else pathext
373
+ for folder in os.environ.get("PATH", "").split(os.pathsep):
374
+ if folder in ("", "."):
375
+ continue
376
+ for ext in exts:
377
+ candidate = os.path.join(folder, name + ext)
378
+ if os.path.isfile(candidate):
379
+ return candidate
380
+ return None
381
+
382
+
383
+ def kill(proc):
384
+ if sys.platform != "win32":
385
+ proc.kill()
386
+ return
387
+ # npx.cmd is cmd.exe running node running the server; kill() would end only cmd.exe.
388
+ subprocess.run(["taskkill", "/F", "/T", "/PID", str(proc.pid)],
389
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
390
+
391
+
392
+ USAGE = """usage: mcp-nap wrap [NAME...] [--idle SECONDS] [--client cursor|vscode]
393
+ mcp-nap unwrap [NAME...] [--client cursor|vscode]
394
+ mcp-nap <name> [--idle SECONDS] [--reauth ARG] -- <command> [args...]
395
+
396
+ --idle defaults to 600 seconds; 0 never stops the server. Without --client, wrap and
397
+ unwrap edit Claude Code's user servers through `claude mcp`."""
398
+
399
+ if sys.platform == "darwin":
400
+ VSCODE_USER = os.path.join("~", "Library", "Application Support", "Code", "User")
401
+ elif os.name == "nt":
402
+ VSCODE_USER = os.path.join(os.environ.get("APPDATA") or os.path.join("~", "AppData", "Roaming"),
403
+ "Code", "User")
404
+ else:
405
+ VSCODE_USER = os.path.join(os.environ.get("XDG_CONFIG_HOME") or os.path.join("~", ".config"),
406
+ "Code", "User")
407
+
408
+ # Clients whose config mcp-nap edits itself: where the file is, the key that holds the
409
+ # servers, and how to pick up a change.
410
+ # Cursor 3.29 starts a new copy of an edited server at once but leaves the old copy, and
411
+ # the one a second window runs, on the old command until a toggle or quit.
412
+ # VS Code 1.129 chat reads the default profile's mcp.json, not ~/.copilot/mcp-config.json.
413
+ # In 1.146 the Copilot agent host behind chat sees an edit on the next message, drops the
414
+ # session and starts every server again on the new command.
415
+ CLIENTS = {
416
+ "cursor": (os.path.join("~", ".cursor", "mcp.json"), "mcpServers",
417
+ "Cursor starts the new command by itself, but copies already running keep "
418
+ "the old one: toggle each changed server off and on in Cursor Settings > "
419
+ "Tools & MCP, or quit and reopen Cursor."),
420
+ "vscode": (os.path.join(VSCODE_USER, "mcp.json"), "servers",
421
+ "VS Code picks up the new command in each chat the next time you send a "
422
+ "message in it, or quit and reopen VS Code."),
423
+ }
424
+
425
+
426
+ def config_path():
427
+ return os.path.join(os.environ.get("CLAUDE_CONFIG_DIR") or os.path.expanduser("~"),
428
+ ".claude.json")
429
+
430
+
431
+ def is_stdio(entry):
432
+ return entry.get("type", "stdio") == "stdio" and "command" in entry
433
+
434
+
435
+ def runner(entry):
436
+ """Which wrapper runs a server (mcp-nap or mcp-lazy) and where its own args start."""
437
+ words = [entry["command"]] + entry.get("args", [])
438
+ # python3 mcp_nap.py, uvx mcp-nap@0.1.0 and a bare mcp-nap all name it in the first two.
439
+ for i, word in enumerate(words[:2]):
440
+ stem = os.path.basename(word).split("@")[0].replace("_", "-")
441
+ if stem.endswith((".py", ".exe")):
442
+ stem = os.path.splitext(stem)[0]
443
+ if stem in ("mcp-nap", "mcp-lazy") and "--" in words[i + 1:]:
444
+ return stem, i
445
+ return None, None
446
+
447
+
448
+ def own_command():
449
+ script = os.path.abspath(sys.argv[0])
450
+ if script.endswith(".py"):
451
+ return [sys.executable, script]
452
+ # A script inside uv's cache is gone after the next `uv cache clean`; go through uvx.
453
+ if os.sep + "uv" + os.sep in script and "archive-v" in script:
454
+ return [on_path("uvx") or "uvx", "mcp-nap"]
455
+ return [script]
456
+
457
+
458
+ def claude_mcp(*args):
459
+ claude = on_path("claude")
460
+ if not claude:
461
+ sys.exit("mcp-nap: no `claude` on PATH; it edits the config so live sessions don't clobber it")
462
+ done = subprocess.run([claude, "mcp", args[0], "-s", "user", *args[1:]],
463
+ capture_output=True, text=True)
464
+ if done.returncode != 0:
465
+ raise OSError((done.stderr or done.stdout).strip())
466
+
467
+
468
+ def wrap_entry(name, entry, idle):
469
+ nap = own_command() + [name] + (["--idle", idle] if idle is not None else [])
470
+ wrapped = {}
471
+ for key, value in entry.items():
472
+ if key == "command":
473
+ wrapped["command"] = nap[0]
474
+ wrapped["args"] = nap[1:] + ["--", entry["command"]] + entry.get("args", [])
475
+ elif key != "args":
476
+ wrapped[key] = value
477
+ return wrapped
478
+
479
+
480
+ def unwrap_entry(entry, start, backups):
481
+ words = [entry["command"]] + entry["args"]
482
+ original = words[words.index("--", start + 1) + 1:]
483
+ unwrapped = {}
484
+ for key, value in entry.items():
485
+ if key == "command":
486
+ unwrapped["command"] = original[0]
487
+ elif key == "args":
488
+ unwrapped["args"] = original[1:]
489
+ else:
490
+ unwrapped[key] = value
491
+ # wrap adds args to a server that had none; only a backup knows it was missing.
492
+ if not original[1:] and any(
493
+ b.get("command") == original[0] and "args" not in b for b in backups):
494
+ del unwrapped["args"]
495
+ return unwrapped
496
+
497
+
498
+ def saved_entries(path, key, name):
499
+ found = []
500
+ for backup in sorted(glob.glob(path + ".mcp-nap-*"), reverse=True):
501
+ try:
502
+ with open(backup, encoding="utf-8") as f:
503
+ found.append(json.load(f)[key][name])
504
+ except (OSError, ValueError, KeyError):
505
+ pass
506
+ return found
507
+
508
+
509
+ def json_layout(text):
510
+ """How text was written: json.dumps arguments, line end, the end of the last line,
511
+ and whether dumping with those gives text back exactly."""
512
+ newline = "\r\n" if "\r\n" in text else "\n"
513
+ body = text.replace("\r\n", "\n")
514
+ end = "\n" if body.endswith("\n") else ""
515
+ config = json.loads(body)
516
+ for indent in (2, 4, "\t"):
517
+ for escaped in (False, True):
518
+ if json.dumps(config, indent=indent, ensure_ascii=escaped) + end == body:
519
+ return {"indent": indent, "ensure_ascii": escaped}, newline, end, True
520
+ first = re.search(r"\n([ \t]+)\S", body)
521
+ indent = 2 if not first else "\t" if first.group(1)[0] == "\t" else len(first.group(1))
522
+ return {"indent": indent, "ensure_ascii": False}, newline, end, False
523
+
524
+
525
+ def replace_file(path, text, mode):
526
+ # Replacing a symlink would cut it loose from the dotfiles repo it points into.
527
+ path = os.path.realpath(path)
528
+ # mkstemp: created 0600 under a fresh name, so the text, tokens and all, is never
529
+ # readable by others and a link planted at a fixed name is never written through.
530
+ # Not path + ".mcp-nap-...": saved_entries reads every file named like that.
531
+ fd, tmp = tempfile.mkstemp(dir=os.path.dirname(path), prefix=os.path.basename(path) + ".",
532
+ suffix=".tmp")
533
+ try:
534
+ with open(fd, "w", encoding="utf-8", newline="") as f:
535
+ os.chmod(tmp, mode)
536
+ f.write(text)
537
+ os.replace(tmp, path)
538
+ except BaseException:
539
+ os.remove(tmp)
540
+ raise
541
+
542
+
543
+ def rewrite(command, argv):
544
+ idle = None
545
+ if "--idle" in argv:
546
+ at = argv.index("--idle")
547
+ idle = argv[at + 1]
548
+ int(idle)
549
+ argv = argv[:at] + argv[at + 2:]
550
+ client = None
551
+ if "--client" in argv:
552
+ at = argv.index("--client")
553
+ client = argv[at + 1]
554
+ argv = argv[:at] + argv[at + 2:]
555
+ if client not in CLIENTS:
556
+ sys.exit("mcp-nap: --client takes " + ", ".join(CLIENTS))
557
+ key = "mcpServers"
558
+ if client:
559
+ path = os.path.expanduser(CLIENTS[client][0])
560
+ key = CLIENTS[client][1]
561
+ try:
562
+ with open(path, encoding="utf-8", newline="") as f:
563
+ text = f.read()
564
+ config = json.loads(text)
565
+ except FileNotFoundError:
566
+ sys.exit("mcp-nap: no %s config at %s" % (client, path))
567
+ except ValueError as err:
568
+ sys.exit("mcp-nap: left %s as it is: not plain JSON, and any comments or "
569
+ "trailing commas would be lost on the way back out (%s)" % (path, err))
570
+ if not isinstance(config, dict):
571
+ sys.exit("mcp-nap: left %s as it is: not a JSON object" % path)
572
+ servers = config.get(key, {})
573
+ else:
574
+ path = config_path()
575
+ with open(path, encoding="utf-8") as f:
576
+ servers = json.load(f).get("mcpServers", {})
577
+ missing = [name for name in argv if name not in servers]
578
+ if missing:
579
+ where = "user-scoped MCP server" if client is None else "MCP server in " + path
580
+ sys.exit("mcp-nap: no %s named %s" % (where, ", ".join(missing)))
581
+ wanted = argv or list(servers)
582
+ changed = {}
583
+ for name in wanted:
584
+ entry = servers[name]
585
+ if not is_stdio(entry):
586
+ print("left %s alone: %s server" % (name, entry.get("type", "url")))
587
+ continue
588
+ if command == "wrap" and entry.get("sandboxEnabled"):
589
+ # VS Code's sandbox lets a server write only its allowWrite paths, ~/.npm and
590
+ # its cwd, so mcp-nap inside it could not write its cache.
591
+ print("left %s alone: sandboxed, and the sandbox would not let mcp-nap write "
592
+ "its cache" % name)
593
+ continue
594
+ tool, start = runner(entry)
595
+ if command == "wrap" and tool:
596
+ print("left %s alone: already runs through %s" % (name, tool))
597
+ elif command == "wrap":
598
+ changed[name] = wrap_entry(name, entry, idle)
599
+ elif tool == "mcp-nap":
600
+ changed[name] = unwrap_entry(entry, start, saved_entries(path, key, name))
601
+ elif argv:
602
+ print("left %s alone: not run by mcp-nap" % name)
603
+ if not changed:
604
+ print("nothing to %s" % command)
605
+ return
606
+ # Two runs inside one second get the same stamp; the first backup may be the only
607
+ # copy of the file as it was, and unwrap reads it.
608
+ stamp = backup = path + time.strftime(".mcp-nap-%Y%m%d-%H%M%S")
609
+ tries = 1
610
+ while os.path.lexists(backup):
611
+ tries += 1
612
+ backup = "%s-%d" % (stamp, tries)
613
+ shutil.copy2(path, backup)
614
+ print("backup: " + backup)
615
+ if client:
616
+ servers.update(changed)
617
+ dumps_args, newline, end, exact = json_layout(text)
618
+ replace_file(path, (json.dumps(config, **dumps_args) + end).replace("\n", newline),
619
+ os.stat(path).st_mode)
620
+ print("%sped: %s" % (command, ", ".join(changed)))
621
+ if not exact:
622
+ print("note: %s was laid out by hand, so it was reformatted; the backup has it "
623
+ "as it was." % path)
624
+ print(CLIENTS[client][2])
625
+ return
626
+ # remove + add-json moves a server to the end, so re-adding every stdio server from
627
+ # the first change on keeps the order. http and sse servers are never removed:
628
+ # remove also deletes their OAuth tokens.
629
+ names = list(servers)
630
+ first = min(names.index(name) for name in changed)
631
+ passed = [n for n in names[first:] if not is_stdio(servers[n])]
632
+ for name in names[first:]:
633
+ if not is_stdio(servers[name]):
634
+ continue
635
+ new = changed.get(name, servers[name])
636
+ claude_mcp("remove", name)
637
+ try:
638
+ claude_mcp("add-json", name, json.dumps(new, ensure_ascii=False))
639
+ except OSError as err:
640
+ claude_mcp("add-json", name, json.dumps(servers[name], ensure_ascii=False))
641
+ sys.exit("mcp-nap: claude mcp add-json %s failed, put the old entry back: %s\n"
642
+ "The file before this run is %s" % (name, err, backup))
643
+ print("%sped: %s" % (command, ", ".join(changed)))
644
+ if passed:
645
+ print("note: the servers after %s in %s changed order, because %s cannot be removed "
646
+ "and re-added without losing its login. The order does not change how Claude "
647
+ "Code runs them." % (names[first], path, ", ".join(passed)))
648
+ print("Restart open Claude Code sessions to pick this up.")
649
+
650
+
651
+ def main(argv=None):
652
+ argv = sys.argv[1:] if argv is None else argv
653
+ if argv[:1] == ["--version"]:
654
+ print("mcp-nap", __version__)
655
+ return
656
+ if argv[:1] in (["--help"], ["-h"]):
657
+ print(USAGE)
658
+ return
659
+ if argv[:1] in (["wrap"], ["unwrap"]) and "--" not in argv:
660
+ rewrite(argv[0], argv[1:])
661
+ return
662
+ if "--" not in argv or len(argv) < 3:
663
+ sys.exit(USAGE)
664
+ split = argv.index("--")
665
+ opts, cmd = argv[:split], argv[split + 1:]
666
+ idle = 600
667
+ if "--idle" in opts:
668
+ idle = int(opts[opts.index("--idle") + 1])
669
+ reauth = None
670
+ if "--reauth" in opts:
671
+ reauth = opts[opts.index("--reauth") + 1]
672
+ Lazy(opts[0], cmd, idle, reauth).run()
673
+
674
+
675
+ if __name__ == "__main__":
676
+ main()