mcp-to-cli-kit 0.1.0__tar.gz → 0.3.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.
Files changed (40) hide show
  1. {mcp_to_cli_kit-0.1.0 → mcp_to_cli_kit-0.3.0}/PKG-INFO +101 -2
  2. {mcp_to_cli_kit-0.1.0 → mcp_to_cli_kit-0.3.0}/README.md +100 -1
  3. {mcp_to_cli_kit-0.1.0 → mcp_to_cli_kit-0.3.0}/src/mcp_to_cli_kit/cache.py +21 -15
  4. {mcp_to_cli_kit-0.1.0 → mcp_to_cli_kit-0.3.0}/src/mcp_to_cli_kit/cli.py +434 -47
  5. {mcp_to_cli_kit-0.1.0 → mcp_to_cli_kit-0.3.0}/src/mcp_to_cli_kit/client.py +91 -16
  6. {mcp_to_cli_kit-0.1.0 → mcp_to_cli_kit-0.3.0}/src/mcp_to_cli_kit/config.py +342 -30
  7. mcp_to_cli_kit-0.3.0/src/mcp_to_cli_kit/config_view.py +104 -0
  8. mcp_to_cli_kit-0.3.0/src/mcp_to_cli_kit/files.py +29 -0
  9. mcp_to_cli_kit-0.3.0/src/mcp_to_cli_kit/oauth.py +813 -0
  10. mcp_to_cli_kit-0.3.0/src/mcp_to_cli_kit/redaction.py +83 -0
  11. {mcp_to_cli_kit-0.1.0 → mcp_to_cli_kit-0.3.0}/tests/conftest.py +24 -0
  12. mcp_to_cli_kit-0.3.0/tests/fixture_auth.py +300 -0
  13. {mcp_to_cli_kit-0.1.0 → mcp_to_cli_kit-0.3.0}/tests/fixture_server.py +15 -0
  14. {mcp_to_cli_kit-0.1.0 → mcp_to_cli_kit-0.3.0}/tests/test_cli.py +30 -0
  15. mcp_to_cli_kit-0.3.0/tests/test_config_command.py +290 -0
  16. mcp_to_cli_kit-0.3.0/tests/test_expansion.py +520 -0
  17. {mcp_to_cli_kit-0.1.0 → mcp_to_cli_kit-0.3.0}/tests/test_mounts.py +1 -0
  18. mcp_to_cli_kit-0.3.0/tests/test_oauth.py +449 -0
  19. mcp_to_cli_kit-0.3.0/tests/test_redaction.py +49 -0
  20. mcp_to_cli_kit-0.3.0/tests/test_strip_prefixes.py +379 -0
  21. {mcp_to_cli_kit-0.1.0 → mcp_to_cli_kit-0.3.0}/tests/test_tool_groups.py +1 -1
  22. {mcp_to_cli_kit-0.1.0 → mcp_to_cli_kit-0.3.0}/.editorconfig +0 -0
  23. {mcp_to_cli_kit-0.1.0 → mcp_to_cli_kit-0.3.0}/.github/workflows/ci.yml +0 -0
  24. {mcp_to_cli_kit-0.1.0 → mcp_to_cli_kit-0.3.0}/.github/workflows/publish.yml +0 -0
  25. {mcp_to_cli_kit-0.1.0 → mcp_to_cli_kit-0.3.0}/.gitignore +0 -0
  26. {mcp_to_cli_kit-0.1.0 → mcp_to_cli_kit-0.3.0}/.python-version +0 -0
  27. {mcp_to_cli_kit-0.1.0 → mcp_to_cli_kit-0.3.0}/LICENSE +0 -0
  28. {mcp_to_cli_kit-0.1.0 → mcp_to_cli_kit-0.3.0}/pyproject.toml +0 -0
  29. {mcp_to_cli_kit-0.1.0 → mcp_to_cli_kit-0.3.0}/src/mcp_to_cli_kit/__init__.py +0 -0
  30. {mcp_to_cli_kit-0.1.0 → mcp_to_cli_kit-0.3.0}/src/mcp_to_cli_kit/agent.py +0 -0
  31. {mcp_to_cli_kit-0.1.0 → mcp_to_cli_kit-0.3.0}/src/mcp_to_cli_kit/arguments.py +0 -0
  32. {mcp_to_cli_kit-0.1.0 → mcp_to_cli_kit-0.3.0}/src/mcp_to_cli_kit/output.py +0 -0
  33. {mcp_to_cli_kit-0.1.0 → mcp_to_cli_kit-0.3.0}/src/mcp_to_cli_kit/py.typed +0 -0
  34. {mcp_to_cli_kit-0.1.0 → mcp_to_cli_kit-0.3.0}/tests/test_agent.py +0 -0
  35. {mcp_to_cli_kit-0.1.0 → mcp_to_cli_kit-0.3.0}/tests/test_arguments.py +0 -0
  36. {mcp_to_cli_kit-0.1.0 → mcp_to_cli_kit-0.3.0}/tests/test_client.py +0 -0
  37. {mcp_to_cli_kit-0.1.0 → mcp_to_cli_kit-0.3.0}/tests/test_config.py +0 -0
  38. {mcp_to_cli_kit-0.1.0 → mcp_to_cli_kit-0.3.0}/tests/test_output.py +0 -0
  39. {mcp_to_cli_kit-0.1.0 → mcp_to_cli_kit-0.3.0}/tests/test_schema.py +0 -0
  40. {mcp_to_cli_kit-0.1.0 → mcp_to_cli_kit-0.3.0}/uv.lock +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: mcp-to-cli-kit
3
- Version: 0.1.0
3
+ Version: 0.3.0
4
4
  Summary: Build a typed command-line interface for one or more remote MCP servers
5
5
  Project-URL: Homepage, https://github.com/fprochazka/mcp-to-cli-kit
6
6
  Project-URL: Repository, https://github.com/fprochazka/mcp-to-cli-kit
@@ -149,6 +149,61 @@ servers:
149
149
  sse_read_timeout: 100 # seconds to wait for an answer, streamed or not
150
150
  ```
151
151
 
152
+ ### Environment variables in values
153
+
154
+ The `url` and the `headers` values may refer to environment variables as `${NAME}`, so a token can stay out of the config file and the code default:
155
+
156
+ ```yaml
157
+ servers:
158
+ example:
159
+ url: https://${EXAMPLE_HOST}/mcp
160
+ headers:
161
+ Authorization: "Bearer ${EXAMPLE_TOKEN}"
162
+ ```
163
+
164
+ - References are expanded when the CLI contacts the server, never when the config is loaded. An unset variable therefore fails only a command that needs that server, with a config error (exit code 2) that names the variable and the server, and never shows a value. An empty variable counts as set.
165
+ - `--help`, a tool's `--help` and `schema` still work offline from a fresh tool cache when the variable is unset. With an expired cache the CLI warns and uses it, as when the server is down.
166
+ - A template can come from any layer: the code default, the config file, or an environment variable such as `EXAMPLE_TOOL_SERVERS__EXAMPLE__HEADERS__AUTHORIZATION='Bearer ${EXAMPLE_TOKEN}'`.
167
+ - `$${` is a literal `${`. A `$` not followed by `{` stays as it is. A `${` without a closing `}`, or one that does not enclose a variable name (letters, digits and `_`), is a config error when the config is loaded.
168
+ - Only `url`, the header values, `auth.client_id` and `auth.client_secret` are expanded. Names (servers, mounts, tool groups, tools) and help texts are taken as written.
169
+ - A URL with references is checked once it is expanded: it must be a valid http(s) URL, and no value may move text into another part of the URL (a `/`, `?`, `#` or `@` in a password, for example), so percent-encode such characters in the variable. An expanded header value must not hold control or non-ASCII characters. Each of these is a config error that names the variable, never its value.
170
+ - Error messages show the URL as configured, with `${NAME}` unexpanded and without its userinfo and query. The parts that carry secrets (the values of the variables in the headers, and the userinfo, password, query and fragment of the expanded URL, also in their percent-encoded forms, if they are 4 characters or longer) are also replaced in transport errors and in the `-v` / `-vv` log. Host, port and path values are not secrets and are shown.
171
+ - The tool cache remembers a hash of the URL as configured and one of the expanded URL. Pointing a variable at another server fetches that server's tools; with the variable unset, the cache of the configured URL is used.
172
+
173
+ ### Signing in with OAuth
174
+
175
+ A server that follows the [MCP authorization spec](https://modelcontextprotocol.io/specification/2025-11-25/basic/authorization) gets an `auth` key instead of an `Authorization` header. The kit needs a pre-registered OAuth client: it does not register one dynamically.
176
+
177
+ ```yaml
178
+ servers:
179
+ example:
180
+ url: https://mcp.example.com/mcp
181
+ auth:
182
+ type: oauth
183
+ client_id: 1234-abcd.apps.googleusercontent.com
184
+ client_secret: GOCSPX-... # optional; ${NAME} references work here and in client_id
185
+ scopes: [openid, email] # optional; default: the scopes the server announces
186
+ bearer: access_token # or id_token, for a proxy that wants an OpenID Connect ID token
187
+ authorization_server: null # optional: the issuer, for a server without protected resource metadata
188
+ redirect_port: 0 # optional: a fixed loopback port, for a client registered with an exact redirect URI
189
+ resource: true # optional: false leaves out the RFC 8707 resource parameter
190
+ ```
191
+
192
+ ```console
193
+ $ example-tool auth login # opens the browser, then stores the tokens
194
+ $ example-tool auth status # who is signed in, as JSON, without the tokens
195
+ $ example-tool auth logout # deletes the stored tokens; --revoke also revokes the sign-in
196
+ ```
197
+
198
+ - Only `auth login` signs in. It finds the authorization server from the server's protected resource metadata, opens the browser with PKCE (S256) and a redirect to `http://127.0.0.1:<port>/callback`, and waits up to 5 minutes (`--timeout`). It also prints the sign-in address; with `--no-browser` it only prints it. Without a server name it signs in to every server that uses OAuth.
199
+ - Every other command reads the stored tokens and refreshes them when less than 5 minutes remain. It never opens a browser: when there is no sign-in, or the authorization server ended it, the command exits with 4 and names the `auth login` command to run. An AI agent gets that answer at once and can ask the user to sign in.
200
+ - When the server answers 401 to a token the CLI considers valid, the CLI refreshes the token once and sends the request again. The request never reached the server, so this is safe for a tool call too.
201
+ - The tokens are stored in `$XDG_STATE_HOME/<bin>/oauth/<server>.json` (`~/.local/state/...` by default), readable by the owner only. The file records the server URL and the client it was issued for; after either changes in the config, the CLI counts as signed out and never sends the old token. Parallel commands refresh under a file lock, so one refresh serves them all.
202
+ - The client secret is masked in `config`, and the secret and every token are kept out of error messages and the `-v` / `-vv` log.
203
+ - A Google "Desktop app" client is a public client: Google expects its secret to ship with the app, so a consumer can put it in its code default. With Google, `logout --revoke` revokes the sign-in of every app that uses the same client.
204
+
205
+ `auth` is a reserved command name, like `schema` and `config`. It shows in the help only when a server uses OAuth.
206
+
152
207
  ### Several servers in one bin
153
208
 
154
209
  A bin can serve several MCP servers. Each server says where its tools appear with `mount`:
@@ -169,6 +224,22 @@ Each server keeps its own session, cache file (`<cache>/<bin>/<server>.json`), h
169
224
 
170
225
  Two servers must not produce the same command name. When the tool lists show that they do (two root servers with a tool of the same name, or a group named like a top-level tool), the CLI stops with a config error that names both servers; give one of them a group or prefix mount, or hide the tool with `hidden_tools`. Calling a group checks the other servers only from what is already known (their caches), so a clash with a server whose tools were never fetched surfaces in the top-level `--help`. When a command resolves on one server while another server that could also define it cannot be reached, the CLI runs it and warns that the other server could not be checked.
171
226
 
227
+ ### Stripping prefixes from tool names
228
+
229
+ Some servers put their own name in front of every tool (`vendor-x_list`, `vendor-x_get`). `strip_prefixes` removes it from the command names:
230
+
231
+ ```yaml
232
+ servers:
233
+ example:
234
+ url: https://mcp.example.com/mcp
235
+ strip_prefixes: [vendor-x_, vendor_x-] # vendor-x_list -> example-tool list
236
+ ```
237
+
238
+ - The first prefix in the list that a tool name starts with is stripped. A name that equals the prefix is kept.
239
+ - It works in every mount mode and happens before tool groups and mounts: `tool_groups` prefixes match the stripped names, and a group or prefix mount applies to the stripped command (`prefix: "v-"` gives `example-tool v-list`).
240
+ - The tool's own name stays an alias (`example-tool vendor-x_list`), and `hidden_tools` still lists tools by their own names.
241
+ - When a stripped name would clash with another tool or a tool group of the same server (`vendor-x_list` next to a plain `list`), that tool keeps its full name and the CLI warns on stderr, so neither tool hides the other; hide one of them with `hidden_tools` to silence it. A clash with another server's tool is a config error, as for any other command name.
242
+
172
243
  ### Tool groups and hidden tools
173
244
 
174
245
  A server with many tools can split them into subcommands by tool-name prefix:
@@ -210,6 +281,32 @@ A property named like a built-in option (`help`, `input-json`, `arg-file`, `json
210
281
 
211
282
  `schema` is a built-in command name: a tool whose command would be `schema` is renamed to `schema-tool`, and no group mount or tool group may be called `schema`.
212
283
 
284
+ ### The config command
285
+
286
+ `example-tool config` prints the effective configuration as JSON: the code default, the config file and the environment variables merged, with every default filled in. Next to it, it shows the config file that was looked for (`config_file`), whether it was loaded (`config_file_loaded`), the environment variable prefix (`env_prefix`) and the names of the environment variables that were applied (`env_applied`), never their values.
287
+
288
+ ```console
289
+ $ example-tool config --pretty
290
+ {
291
+ "config_file": "/home/me/.config/example-tool/config.yaml",
292
+ "config_file_loaded": true,
293
+ "env_prefix": "EXAMPLE_TOOL_",
294
+ "env_applied": ["EXAMPLE_TOOL_SERVERS__EXAMPLE__TIMEOUT"],
295
+ "config": {"help": null, "servers": {"example": {"url": "https://mcp.example.com/mcp", "headers": {"Authorization": "Bearer ${EXAMPLE_TOKEN}"}, ...}}}
296
+ }
297
+ ```
298
+
299
+ - It reads the configuration only. It loads no tool list, sends nothing to any server and needs no cache, so it works offline and with unset variables.
300
+ - `${NAME}` references are shown as written, never expanded.
301
+ - Literal text that may be a secret is masked as `***` plus its last 4 characters, or only `***` when it is shorter than 12 characters. These are masked:
302
+ - every header value, except `Accept`, `Content-Type`, `User-Agent` and `X-Mcp-Client` (matched in any case), which are shown as written. A leading `Bearer`, `Basic`, `Token`, `Digest`, `Bot` or `ApiKey` followed by more text stays readable, as in `Bearer ***abcd`;
303
+ - a URL's whole userinfo (user and password), its query values and its fragment;
304
+ - `auth.client_secret`.
305
+ - Shown as written: the URL's scheme, host, port and path, every other setting (timeouts, mounts, tool groups, hidden tools, prefixes, help texts), and all `${NAME}` references.
306
+ - The output follows the usual modes: compact under an AI agent or with `--json`, indented otherwise or with `--pretty`.
307
+
308
+ `config` and `auth` are reserved command names, like `schema`: a tool whose command would be one of them is renamed with a `-tool` suffix, and no group mount or tool group may take them.
309
+
213
310
  ### Output and exit codes
214
311
 
215
312
  Under an AI coding agent (detected from its environment variables), or with `--json`, the result is printed exactly as the server sent it. Otherwise, or with `--pretty`, JSON is indented with `indent=2` and non-ASCII text stays readable. Several content items become one JSON array. Nothing is ever wrapped to the terminal width.
@@ -220,17 +317,19 @@ Under an AI coding agent (detected from its environment variables), or with `--j
220
317
  | 1 | The tool reported an error; its text is on stderr |
221
318
  | 2 | Usage or configuration error |
222
319
  | 3 | The server could not be reached or did not speak MCP |
320
+ | 4 | The server needs a sign-in that is missing, expired or refused; run `<bin> auth login` |
223
321
 
224
322
  Other global options: `--refresh-tools` fetches the tool list again, `-v` / `-vv` log to stderr, `--version`. Every request carries an `X-Mcp-Client: <bin>/<version> (mcp-to-cli-kit <version>)` header.
225
323
 
226
324
  When the server cannot be reached, an expired tool cache is used with a warning. `initialize` and `tools/list` are retried twice on connect errors, timeouts and HTTP 502/503/504; a tool call is retried only when it never reached the server. Ctrl-C abandons the request in flight and exits with 130.
227
325
 
228
- Config and cache live under `$XDG_CONFIG_HOME` and `$XDG_CACHE_HOME` when those are set, and under `~/.config` and `~/.cache` otherwise.
326
+ Config, cache and OAuth tokens live under `$XDG_CONFIG_HOME`, `$XDG_CACHE_HOME` and `$XDG_STATE_HOME` when those are set, and under `~/.config`, `~/.cache` and `~/.local/state` otherwise.
229
327
 
230
328
  ## Troubleshooting
231
329
 
232
330
  - **A call ends with "timed out after 100s".** The server took longer than `sse_read_timeout`, which defaults to 100 seconds so that a coding agent's shell tool (often limited to 120 seconds) sees this error instead of killing the command. Raise `sse_read_timeout` for that server when its tools are legitimately slow. Timeouts exit with 3, never with 1, because the tool's own outcome is unknown.
233
331
  - **A call hangs until that timeout although the server already failed.** When a server or proxy cuts a streamed (SSE) answer in the middle, the MCP SDK swallows the broken stream and offers no hook to notice it, so the request ends only with the read timeout. A plain JSON answer cut the same way fails at once.
332
+ - **A command exits with 4 although `auth login` succeeded.** The server refused the token even after a refresh. If the server sits behind a proxy that wants another kind of token, switch `auth.bearer` between `access_token` and `id_token`; the stored sign-in holds both, so no new sign-in is needed. Otherwise the account may lack access to the server.
234
333
  - **Something else.** Run with `-v` to see what the CLI does, or `-vv` to also see the HTTP traffic and the MCP SDK's own log.
235
334
 
236
335
  ## License
@@ -117,6 +117,61 @@ servers:
117
117
  sse_read_timeout: 100 # seconds to wait for an answer, streamed or not
118
118
  ```
119
119
 
120
+ ### Environment variables in values
121
+
122
+ The `url` and the `headers` values may refer to environment variables as `${NAME}`, so a token can stay out of the config file and the code default:
123
+
124
+ ```yaml
125
+ servers:
126
+ example:
127
+ url: https://${EXAMPLE_HOST}/mcp
128
+ headers:
129
+ Authorization: "Bearer ${EXAMPLE_TOKEN}"
130
+ ```
131
+
132
+ - References are expanded when the CLI contacts the server, never when the config is loaded. An unset variable therefore fails only a command that needs that server, with a config error (exit code 2) that names the variable and the server, and never shows a value. An empty variable counts as set.
133
+ - `--help`, a tool's `--help` and `schema` still work offline from a fresh tool cache when the variable is unset. With an expired cache the CLI warns and uses it, as when the server is down.
134
+ - A template can come from any layer: the code default, the config file, or an environment variable such as `EXAMPLE_TOOL_SERVERS__EXAMPLE__HEADERS__AUTHORIZATION='Bearer ${EXAMPLE_TOKEN}'`.
135
+ - `$${` is a literal `${`. A `$` not followed by `{` stays as it is. A `${` without a closing `}`, or one that does not enclose a variable name (letters, digits and `_`), is a config error when the config is loaded.
136
+ - Only `url`, the header values, `auth.client_id` and `auth.client_secret` are expanded. Names (servers, mounts, tool groups, tools) and help texts are taken as written.
137
+ - A URL with references is checked once it is expanded: it must be a valid http(s) URL, and no value may move text into another part of the URL (a `/`, `?`, `#` or `@` in a password, for example), so percent-encode such characters in the variable. An expanded header value must not hold control or non-ASCII characters. Each of these is a config error that names the variable, never its value.
138
+ - Error messages show the URL as configured, with `${NAME}` unexpanded and without its userinfo and query. The parts that carry secrets (the values of the variables in the headers, and the userinfo, password, query and fragment of the expanded URL, also in their percent-encoded forms, if they are 4 characters or longer) are also replaced in transport errors and in the `-v` / `-vv` log. Host, port and path values are not secrets and are shown.
139
+ - The tool cache remembers a hash of the URL as configured and one of the expanded URL. Pointing a variable at another server fetches that server's tools; with the variable unset, the cache of the configured URL is used.
140
+
141
+ ### Signing in with OAuth
142
+
143
+ A server that follows the [MCP authorization spec](https://modelcontextprotocol.io/specification/2025-11-25/basic/authorization) gets an `auth` key instead of an `Authorization` header. The kit needs a pre-registered OAuth client: it does not register one dynamically.
144
+
145
+ ```yaml
146
+ servers:
147
+ example:
148
+ url: https://mcp.example.com/mcp
149
+ auth:
150
+ type: oauth
151
+ client_id: 1234-abcd.apps.googleusercontent.com
152
+ client_secret: GOCSPX-... # optional; ${NAME} references work here and in client_id
153
+ scopes: [openid, email] # optional; default: the scopes the server announces
154
+ bearer: access_token # or id_token, for a proxy that wants an OpenID Connect ID token
155
+ authorization_server: null # optional: the issuer, for a server without protected resource metadata
156
+ redirect_port: 0 # optional: a fixed loopback port, for a client registered with an exact redirect URI
157
+ resource: true # optional: false leaves out the RFC 8707 resource parameter
158
+ ```
159
+
160
+ ```console
161
+ $ example-tool auth login # opens the browser, then stores the tokens
162
+ $ example-tool auth status # who is signed in, as JSON, without the tokens
163
+ $ example-tool auth logout # deletes the stored tokens; --revoke also revokes the sign-in
164
+ ```
165
+
166
+ - Only `auth login` signs in. It finds the authorization server from the server's protected resource metadata, opens the browser with PKCE (S256) and a redirect to `http://127.0.0.1:<port>/callback`, and waits up to 5 minutes (`--timeout`). It also prints the sign-in address; with `--no-browser` it only prints it. Without a server name it signs in to every server that uses OAuth.
167
+ - Every other command reads the stored tokens and refreshes them when less than 5 minutes remain. It never opens a browser: when there is no sign-in, or the authorization server ended it, the command exits with 4 and names the `auth login` command to run. An AI agent gets that answer at once and can ask the user to sign in.
168
+ - When the server answers 401 to a token the CLI considers valid, the CLI refreshes the token once and sends the request again. The request never reached the server, so this is safe for a tool call too.
169
+ - The tokens are stored in `$XDG_STATE_HOME/<bin>/oauth/<server>.json` (`~/.local/state/...` by default), readable by the owner only. The file records the server URL and the client it was issued for; after either changes in the config, the CLI counts as signed out and never sends the old token. Parallel commands refresh under a file lock, so one refresh serves them all.
170
+ - The client secret is masked in `config`, and the secret and every token are kept out of error messages and the `-v` / `-vv` log.
171
+ - A Google "Desktop app" client is a public client: Google expects its secret to ship with the app, so a consumer can put it in its code default. With Google, `logout --revoke` revokes the sign-in of every app that uses the same client.
172
+
173
+ `auth` is a reserved command name, like `schema` and `config`. It shows in the help only when a server uses OAuth.
174
+
120
175
  ### Several servers in one bin
121
176
 
122
177
  A bin can serve several MCP servers. Each server says where its tools appear with `mount`:
@@ -137,6 +192,22 @@ Each server keeps its own session, cache file (`<cache>/<bin>/<server>.json`), h
137
192
 
138
193
  Two servers must not produce the same command name. When the tool lists show that they do (two root servers with a tool of the same name, or a group named like a top-level tool), the CLI stops with a config error that names both servers; give one of them a group or prefix mount, or hide the tool with `hidden_tools`. Calling a group checks the other servers only from what is already known (their caches), so a clash with a server whose tools were never fetched surfaces in the top-level `--help`. When a command resolves on one server while another server that could also define it cannot be reached, the CLI runs it and warns that the other server could not be checked.
139
194
 
195
+ ### Stripping prefixes from tool names
196
+
197
+ Some servers put their own name in front of every tool (`vendor-x_list`, `vendor-x_get`). `strip_prefixes` removes it from the command names:
198
+
199
+ ```yaml
200
+ servers:
201
+ example:
202
+ url: https://mcp.example.com/mcp
203
+ strip_prefixes: [vendor-x_, vendor_x-] # vendor-x_list -> example-tool list
204
+ ```
205
+
206
+ - The first prefix in the list that a tool name starts with is stripped. A name that equals the prefix is kept.
207
+ - It works in every mount mode and happens before tool groups and mounts: `tool_groups` prefixes match the stripped names, and a group or prefix mount applies to the stripped command (`prefix: "v-"` gives `example-tool v-list`).
208
+ - The tool's own name stays an alias (`example-tool vendor-x_list`), and `hidden_tools` still lists tools by their own names.
209
+ - When a stripped name would clash with another tool or a tool group of the same server (`vendor-x_list` next to a plain `list`), that tool keeps its full name and the CLI warns on stderr, so neither tool hides the other; hide one of them with `hidden_tools` to silence it. A clash with another server's tool is a config error, as for any other command name.
210
+
140
211
  ### Tool groups and hidden tools
141
212
 
142
213
  A server with many tools can split them into subcommands by tool-name prefix:
@@ -178,6 +249,32 @@ A property named like a built-in option (`help`, `input-json`, `arg-file`, `json
178
249
 
179
250
  `schema` is a built-in command name: a tool whose command would be `schema` is renamed to `schema-tool`, and no group mount or tool group may be called `schema`.
180
251
 
252
+ ### The config command
253
+
254
+ `example-tool config` prints the effective configuration as JSON: the code default, the config file and the environment variables merged, with every default filled in. Next to it, it shows the config file that was looked for (`config_file`), whether it was loaded (`config_file_loaded`), the environment variable prefix (`env_prefix`) and the names of the environment variables that were applied (`env_applied`), never their values.
255
+
256
+ ```console
257
+ $ example-tool config --pretty
258
+ {
259
+ "config_file": "/home/me/.config/example-tool/config.yaml",
260
+ "config_file_loaded": true,
261
+ "env_prefix": "EXAMPLE_TOOL_",
262
+ "env_applied": ["EXAMPLE_TOOL_SERVERS__EXAMPLE__TIMEOUT"],
263
+ "config": {"help": null, "servers": {"example": {"url": "https://mcp.example.com/mcp", "headers": {"Authorization": "Bearer ${EXAMPLE_TOKEN}"}, ...}}}
264
+ }
265
+ ```
266
+
267
+ - It reads the configuration only. It loads no tool list, sends nothing to any server and needs no cache, so it works offline and with unset variables.
268
+ - `${NAME}` references are shown as written, never expanded.
269
+ - Literal text that may be a secret is masked as `***` plus its last 4 characters, or only `***` when it is shorter than 12 characters. These are masked:
270
+ - every header value, except `Accept`, `Content-Type`, `User-Agent` and `X-Mcp-Client` (matched in any case), which are shown as written. A leading `Bearer`, `Basic`, `Token`, `Digest`, `Bot` or `ApiKey` followed by more text stays readable, as in `Bearer ***abcd`;
271
+ - a URL's whole userinfo (user and password), its query values and its fragment;
272
+ - `auth.client_secret`.
273
+ - Shown as written: the URL's scheme, host, port and path, every other setting (timeouts, mounts, tool groups, hidden tools, prefixes, help texts), and all `${NAME}` references.
274
+ - The output follows the usual modes: compact under an AI agent or with `--json`, indented otherwise or with `--pretty`.
275
+
276
+ `config` and `auth` are reserved command names, like `schema`: a tool whose command would be one of them is renamed with a `-tool` suffix, and no group mount or tool group may take them.
277
+
181
278
  ### Output and exit codes
182
279
 
183
280
  Under an AI coding agent (detected from its environment variables), or with `--json`, the result is printed exactly as the server sent it. Otherwise, or with `--pretty`, JSON is indented with `indent=2` and non-ASCII text stays readable. Several content items become one JSON array. Nothing is ever wrapped to the terminal width.
@@ -188,17 +285,19 @@ Under an AI coding agent (detected from its environment variables), or with `--j
188
285
  | 1 | The tool reported an error; its text is on stderr |
189
286
  | 2 | Usage or configuration error |
190
287
  | 3 | The server could not be reached or did not speak MCP |
288
+ | 4 | The server needs a sign-in that is missing, expired or refused; run `<bin> auth login` |
191
289
 
192
290
  Other global options: `--refresh-tools` fetches the tool list again, `-v` / `-vv` log to stderr, `--version`. Every request carries an `X-Mcp-Client: <bin>/<version> (mcp-to-cli-kit <version>)` header.
193
291
 
194
292
  When the server cannot be reached, an expired tool cache is used with a warning. `initialize` and `tools/list` are retried twice on connect errors, timeouts and HTTP 502/503/504; a tool call is retried only when it never reached the server. Ctrl-C abandons the request in flight and exits with 130.
195
293
 
196
- Config and cache live under `$XDG_CONFIG_HOME` and `$XDG_CACHE_HOME` when those are set, and under `~/.config` and `~/.cache` otherwise.
294
+ Config, cache and OAuth tokens live under `$XDG_CONFIG_HOME`, `$XDG_CACHE_HOME` and `$XDG_STATE_HOME` when those are set, and under `~/.config`, `~/.cache` and `~/.local/state` otherwise.
197
295
 
198
296
  ## Troubleshooting
199
297
 
200
298
  - **A call ends with "timed out after 100s".** The server took longer than `sse_read_timeout`, which defaults to 100 seconds so that a coding agent's shell tool (often limited to 120 seconds) sees this error instead of killing the command. Raise `sse_read_timeout` for that server when its tools are legitimately slow. Timeouts exit with 3, never with 1, because the tool's own outcome is unknown.
201
299
  - **A call hangs until that timeout although the server already failed.** When a server or proxy cuts a streamed (SSE) answer in the middle, the MCP SDK swallows the broken stream and offers no hook to notice it, so the request ends only with the read timeout. A plain JSON answer cut the same way fails at once.
300
+ - **A command exits with 4 although `auth login` succeeded.** The server refused the token even after a refresh. If the server sits behind a proxy that wants another kind of token, switch `auth.bearer` between `access_token` and `id_token`; the stored sign-in holds both, so no new sign-in is needed. Otherwise the account may lack access to the server.
202
301
  - **Something else.** Run with `-v` to see what the CLI does, or `-vv` to also see the HTTP traffic and the MCP SDK's own log.
203
302
 
204
303
  ## License
@@ -6,6 +6,11 @@ A cache entry is fresh for an hour. An expired entry is still kept: when the ser
6
6
  be reached, the CLI falls back to it rather than failing to know its own commands. The entry
7
7
  records a hash of the server URL, never the URL itself, which may carry a token; an entry
8
8
  written for another URL is ignored.
9
+
10
+ A configured URL may be a template with ``${NAME}`` references. The entry then records a hash
11
+ of the template and one of the expanded URL. When the variables are set, both must match, so
12
+ pointing a variable at another server does not reuse the old server's tools; when one is not
13
+ set, the template alone decides, so ``--help`` still lists the tools offline.
9
14
  """
10
15
 
11
16
  from __future__ import annotations
@@ -13,14 +18,13 @@ from __future__ import annotations
13
18
  import hashlib
14
19
  import json
15
20
  import logging
16
- import os
17
- import tempfile
18
21
  import time
19
22
  from dataclasses import dataclass
20
23
  from pathlib import Path
21
24
  from typing import Any
22
25
 
23
26
  from mcp_to_cli_kit.config import xdg_directory
27
+ from mcp_to_cli_kit.files import write_private
24
28
 
25
29
  logger = logging.getLogger(__name__)
26
30
 
@@ -60,8 +64,14 @@ class SchemaCache:
60
64
  """The cache file of one server."""
61
65
  return self.directory / f"{server}.json"
62
66
 
63
- def load(self, server: str, url: str) -> CachedTools | None:
64
- """Return the cached tools of a server, fresh or expired, or None when there is no usable entry."""
67
+ def load(self, server: str, url: str, resolved_url: str | None = None) -> CachedTools | None:
68
+ """Return the cached tools of a server, fresh or expired, or None when there is no usable entry.
69
+
70
+ Args:
71
+ server: The server's name.
72
+ url: The URL as configured, a template or not.
73
+ resolved_url: The URL with its variables expanded, or None when they cannot be.
74
+ """
65
75
  path = self.path(server)
66
76
  try:
67
77
  content = json.loads(path.read_text(encoding="utf-8"))
@@ -75,6 +85,7 @@ class SchemaCache:
75
85
  not isinstance(content, dict)
76
86
  or content.get("version") != _FORMAT_VERSION
77
87
  or content.get("url_sha256") != _url_hash(url)
88
+ or (resolved_url not in (None, url) and content.get("resolved_url_sha256") != _url_hash(resolved_url))
78
89
  or not isinstance(content.get("tools"), list)
79
90
  or not isinstance(content.get("fetched_at"), int | float)
80
91
  ):
@@ -86,20 +97,15 @@ class SchemaCache:
86
97
  tools = [tool for tool in content["tools"] if isinstance(tool, dict)]
87
98
  return CachedTools(tools=tools, fetched_at=fetched_at, fresh=0 <= age < self.ttl_seconds)
88
99
 
89
- def save(self, server: str, url: str, tools: list[dict[str, Any]]) -> None:
100
+ def save(self, server: str, url: str, tools: list[dict[str, Any]], resolved_url: str | None = None) -> None:
90
101
  """Write a server's tools atomically. A failure to write is logged, never raised."""
91
- content = {"version": _FORMAT_VERSION, "url_sha256": _url_hash(url), "fetched_at": time.time(), "tools": tools}
102
+ content: dict[str, Any] = {"version": _FORMAT_VERSION, "url_sha256": _url_hash(url)}
103
+ if resolved_url is not None and resolved_url != url:
104
+ content["resolved_url_sha256"] = _url_hash(resolved_url)
105
+ content.update(fetched_at=time.time(), tools=tools)
92
106
  path = self.path(server)
93
107
  try:
94
- self.directory.mkdir(mode=0o700, parents=True, exist_ok=True)
95
- descriptor, temporary = tempfile.mkstemp(dir=self.directory, prefix=f".{server}.", suffix=".tmp")
96
- try:
97
- with os.fdopen(descriptor, "w", encoding="utf-8") as handle:
98
- json.dump(content, handle, ensure_ascii=False)
99
- os.replace(temporary, path)
100
- except BaseException:
101
- Path(temporary).unlink(missing_ok=True)
102
- raise
108
+ write_private(path, json.dumps(content, ensure_ascii=False))
103
109
  except OSError as error:
104
110
  logger.warning("Cannot write the tool cache %s: %s", path, error)
105
111