mcp-to-cli-kit 0.2.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.2.0 → mcp_to_cli_kit-0.3.0}/PKG-INFO +42 -5
  2. {mcp_to_cli_kit-0.2.0 → mcp_to_cli_kit-0.3.0}/README.md +41 -4
  3. {mcp_to_cli_kit-0.2.0 → mcp_to_cli_kit-0.3.0}/src/mcp_to_cli_kit/cache.py +2 -11
  4. {mcp_to_cli_kit-0.2.0 → mcp_to_cli_kit-0.3.0}/src/mcp_to_cli_kit/cli.py +231 -11
  5. {mcp_to_cli_kit-0.2.0 → mcp_to_cli_kit-0.3.0}/src/mcp_to_cli_kit/client.py +48 -1
  6. {mcp_to_cli_kit-0.2.0 → mcp_to_cli_kit-0.3.0}/src/mcp_to_cli_kit/config.py +93 -23
  7. {mcp_to_cli_kit-0.2.0 → mcp_to_cli_kit-0.3.0}/src/mcp_to_cli_kit/config_view.py +5 -1
  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.2.0 → mcp_to_cli_kit-0.3.0}/tests/conftest.py +15 -0
  11. mcp_to_cli_kit-0.3.0/tests/fixture_auth.py +300 -0
  12. mcp_to_cli_kit-0.3.0/tests/test_oauth.py +449 -0
  13. {mcp_to_cli_kit-0.2.0 → mcp_to_cli_kit-0.3.0}/.editorconfig +0 -0
  14. {mcp_to_cli_kit-0.2.0 → mcp_to_cli_kit-0.3.0}/.github/workflows/ci.yml +0 -0
  15. {mcp_to_cli_kit-0.2.0 → mcp_to_cli_kit-0.3.0}/.github/workflows/publish.yml +0 -0
  16. {mcp_to_cli_kit-0.2.0 → mcp_to_cli_kit-0.3.0}/.gitignore +0 -0
  17. {mcp_to_cli_kit-0.2.0 → mcp_to_cli_kit-0.3.0}/.python-version +0 -0
  18. {mcp_to_cli_kit-0.2.0 → mcp_to_cli_kit-0.3.0}/LICENSE +0 -0
  19. {mcp_to_cli_kit-0.2.0 → mcp_to_cli_kit-0.3.0}/pyproject.toml +0 -0
  20. {mcp_to_cli_kit-0.2.0 → mcp_to_cli_kit-0.3.0}/src/mcp_to_cli_kit/__init__.py +0 -0
  21. {mcp_to_cli_kit-0.2.0 → mcp_to_cli_kit-0.3.0}/src/mcp_to_cli_kit/agent.py +0 -0
  22. {mcp_to_cli_kit-0.2.0 → mcp_to_cli_kit-0.3.0}/src/mcp_to_cli_kit/arguments.py +0 -0
  23. {mcp_to_cli_kit-0.2.0 → mcp_to_cli_kit-0.3.0}/src/mcp_to_cli_kit/output.py +0 -0
  24. {mcp_to_cli_kit-0.2.0 → mcp_to_cli_kit-0.3.0}/src/mcp_to_cli_kit/py.typed +0 -0
  25. {mcp_to_cli_kit-0.2.0 → mcp_to_cli_kit-0.3.0}/src/mcp_to_cli_kit/redaction.py +0 -0
  26. {mcp_to_cli_kit-0.2.0 → mcp_to_cli_kit-0.3.0}/tests/fixture_server.py +0 -0
  27. {mcp_to_cli_kit-0.2.0 → mcp_to_cli_kit-0.3.0}/tests/test_agent.py +0 -0
  28. {mcp_to_cli_kit-0.2.0 → mcp_to_cli_kit-0.3.0}/tests/test_arguments.py +0 -0
  29. {mcp_to_cli_kit-0.2.0 → mcp_to_cli_kit-0.3.0}/tests/test_cli.py +0 -0
  30. {mcp_to_cli_kit-0.2.0 → mcp_to_cli_kit-0.3.0}/tests/test_client.py +0 -0
  31. {mcp_to_cli_kit-0.2.0 → mcp_to_cli_kit-0.3.0}/tests/test_config.py +0 -0
  32. {mcp_to_cli_kit-0.2.0 → mcp_to_cli_kit-0.3.0}/tests/test_config_command.py +0 -0
  33. {mcp_to_cli_kit-0.2.0 → mcp_to_cli_kit-0.3.0}/tests/test_expansion.py +0 -0
  34. {mcp_to_cli_kit-0.2.0 → mcp_to_cli_kit-0.3.0}/tests/test_mounts.py +0 -0
  35. {mcp_to_cli_kit-0.2.0 → mcp_to_cli_kit-0.3.0}/tests/test_output.py +0 -0
  36. {mcp_to_cli_kit-0.2.0 → mcp_to_cli_kit-0.3.0}/tests/test_redaction.py +0 -0
  37. {mcp_to_cli_kit-0.2.0 → mcp_to_cli_kit-0.3.0}/tests/test_schema.py +0 -0
  38. {mcp_to_cli_kit-0.2.0 → mcp_to_cli_kit-0.3.0}/tests/test_strip_prefixes.py +0 -0
  39. {mcp_to_cli_kit-0.2.0 → mcp_to_cli_kit-0.3.0}/tests/test_tool_groups.py +0 -0
  40. {mcp_to_cli_kit-0.2.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.2.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
@@ -165,11 +165,45 @@ servers:
165
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
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
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` and the header values are expanded. Names (servers, mounts, tool groups, tools) and help texts are taken as written.
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
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
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
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
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
+
173
207
  ### Several servers in one bin
174
208
 
175
209
  A bin can serve several MCP servers. Each server says where its tools appear with `mount`:
@@ -266,11 +300,12 @@ $ example-tool config --pretty
266
300
  - `${NAME}` references are shown as written, never expanded.
267
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:
268
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`;
269
- - a URL's whole userinfo (user and password), its query values and its fragment.
303
+ - a URL's whole userinfo (user and password), its query values and its fragment;
304
+ - `auth.client_secret`.
270
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.
271
306
  - The output follows the usual modes: compact under an AI agent or with `--json`, indented otherwise or with `--pretty`.
272
307
 
273
- `config` is a reserved command name, like `schema`: a tool whose command would be `config` is renamed to `config-tool`, and no group mount or tool group may be called `config`.
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.
274
309
 
275
310
  ### Output and exit codes
276
311
 
@@ -282,17 +317,19 @@ Under an AI coding agent (detected from its environment variables), or with `--j
282
317
  | 1 | The tool reported an error; its text is on stderr |
283
318
  | 2 | Usage or configuration error |
284
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` |
285
321
 
286
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.
287
323
 
288
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.
289
325
 
290
- 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.
291
327
 
292
328
  ## Troubleshooting
293
329
 
294
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.
295
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.
296
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.
297
334
 
298
335
  ## License
@@ -133,11 +133,45 @@ servers:
133
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
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
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` and the header values are expanded. Names (servers, mounts, tool groups, tools) and help texts are taken as written.
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
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
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
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
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
+
141
175
  ### Several servers in one bin
142
176
 
143
177
  A bin can serve several MCP servers. Each server says where its tools appear with `mount`:
@@ -234,11 +268,12 @@ $ example-tool config --pretty
234
268
  - `${NAME}` references are shown as written, never expanded.
235
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:
236
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`;
237
- - a URL's whole userinfo (user and password), its query values and its fragment.
271
+ - a URL's whole userinfo (user and password), its query values and its fragment;
272
+ - `auth.client_secret`.
238
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.
239
274
  - The output follows the usual modes: compact under an AI agent or with `--json`, indented otherwise or with `--pretty`.
240
275
 
241
- `config` is a reserved command name, like `schema`: a tool whose command would be `config` is renamed to `config-tool`, and no group mount or tool group may be called `config`.
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.
242
277
 
243
278
  ### Output and exit codes
244
279
 
@@ -250,17 +285,19 @@ Under an AI coding agent (detected from its environment variables), or with `--j
250
285
  | 1 | The tool reported an error; its text is on stderr |
251
286
  | 2 | Usage or configuration error |
252
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` |
253
289
 
254
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.
255
291
 
256
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.
257
293
 
258
- 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.
259
295
 
260
296
  ## Troubleshooting
261
297
 
262
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.
263
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.
264
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.
265
302
 
266
303
  ## License
@@ -18,14 +18,13 @@ from __future__ import annotations
18
18
  import hashlib
19
19
  import json
20
20
  import logging
21
- import os
22
- import tempfile
23
21
  import time
24
22
  from dataclasses import dataclass
25
23
  from pathlib import Path
26
24
  from typing import Any
27
25
 
28
26
  from mcp_to_cli_kit.config import xdg_directory
27
+ from mcp_to_cli_kit.files import write_private
29
28
 
30
29
  logger = logging.getLogger(__name__)
31
30
 
@@ -106,15 +105,7 @@ class SchemaCache:
106
105
  content.update(fetched_at=time.time(), tools=tools)
107
106
  path = self.path(server)
108
107
  try:
109
- self.directory.mkdir(mode=0o700, parents=True, exist_ok=True)
110
- descriptor, temporary = tempfile.mkstemp(dir=self.directory, prefix=f".{server}.", suffix=".tmp")
111
- try:
112
- with os.fdopen(descriptor, "w", encoding="utf-8") as handle:
113
- json.dump(content, handle, ensure_ascii=False)
114
- os.replace(temporary, path)
115
- except BaseException:
116
- Path(temporary).unlink(missing_ok=True)
117
- raise
108
+ write_private(path, json.dumps(content, ensure_ascii=False))
118
109
  except OSError as error:
119
110
  logger.warning("Cannot write the tool cache %s: %s", path, error)
120
111
 
@@ -7,7 +7,8 @@ are eager and ``--help`` is not, so ``--help --config other.yaml`` lists the too
7
7
  other config.
8
8
 
9
9
  Exit codes: 0 on success, 1 when the tool reports an error, 2 for a usage or config error,
10
- 3 when the server cannot be reached or does not speak MCP.
10
+ 3 when the server cannot be reached or does not speak MCP, 4 when a server needs a sign-in
11
+ that is missing, expired or refused.
11
12
  """
12
13
 
13
14
  from __future__ import annotations
@@ -20,13 +21,14 @@ import re
20
21
  import sys
21
22
  from collections.abc import Callable, Mapping, Sequence
22
23
  from dataclasses import dataclass, field, replace
24
+ from datetime import UTC, datetime
23
25
  from pathlib import Path
24
26
  from typing import Any, NoReturn
25
27
 
26
28
  import click
27
29
  from mcp import types
28
30
 
29
- from mcp_to_cli_kit import config_view, redaction
31
+ from mcp_to_cli_kit import config_view, oauth, redaction
30
32
  from mcp_to_cli_kit.arguments import CompiledTool, compile_tool, kebab_case
31
33
  from mcp_to_cli_kit.cache import CachedTools, SchemaCache, default_cache_dir
32
34
  from mcp_to_cli_kit.client import (
@@ -46,10 +48,12 @@ from mcp_to_cli_kit.config import (
46
48
  GroupMount,
47
49
  LoadedConfig,
48
50
  PrefixMount,
51
+ ResolvedServer,
49
52
  ToolGroup,
50
53
  default_config_path,
51
54
  load_config,
52
55
  )
56
+ from mcp_to_cli_kit.oauth import AuthError, AuthTransportError, TokenStore, default_token_dir
53
57
  from mcp_to_cli_kit.output import OutputMode, finish, render, resolve_mode
54
58
  from mcp_to_cli_kit.redaction import RedactingFilter
55
59
 
@@ -65,6 +69,7 @@ For servers that report failures as ordinary text.
65
69
  EXIT_TOOL_ERROR = 1
66
70
  EXIT_USAGE = 2
67
71
  EXIT_TRANSPORT = 3
72
+ EXIT_AUTH = 4
68
73
  EXIT_INTERRUPTED = 130
69
74
 
70
75
  _RUNTIME_KEY = "mcp_to_cli_kit.runtime"
@@ -109,6 +114,12 @@ class TransportFailure(click.ClickException):
109
114
  exit_code = EXIT_TRANSPORT
110
115
 
111
116
 
117
+ class AuthFailure(click.ClickException):
118
+ """A server needs a sign-in that is missing, expired or refused. Printed as one ``Error:`` line."""
119
+
120
+ exit_code = EXIT_AUTH
121
+
122
+
112
123
  @dataclass(frozen=True)
113
124
  class App:
114
125
  """What a consumer hands the kit: everything that does not come from the config."""
@@ -317,6 +328,7 @@ class TopLevelListing:
317
328
  groups: dict[str, str] = field(default_factory=dict)
318
329
  unavailable: dict[str, str] = field(default_factory=dict)
319
330
  unresolved: set[str] = field(default_factory=set)
331
+ unauthenticated: set[str] = field(default_factory=set)
320
332
 
321
333
 
322
334
  @dataclass
@@ -336,14 +348,31 @@ class Runtime:
336
348
 
337
349
  def __post_init__(self) -> None:
338
350
  self.cache = SchemaCache(default_cache_dir(self.app.bin_name))
351
+ self.tokens = TokenStore(default_token_dir(self.app.bin_name))
339
352
  version = self.app.bin_version
340
353
  header = client_header_value(self.app.bin_name, version)
341
354
  client_info = types.Implementation(name=self.app.bin_name, version=version)
342
355
  for name, server in self.loaded.config.servers.items():
343
356
  self.clients[name] = ServerClient(
344
- name, server, header, self.portal, self.app.retry_delays, client_info=client_info
357
+ name,
358
+ server,
359
+ header,
360
+ self.portal,
361
+ self.app.retry_delays,
362
+ client_info=client_info,
363
+ token_store=self.tokens,
364
+ login_command=self.login_command(name),
345
365
  )
346
366
 
367
+ def oauth_servers(self) -> list[str]:
368
+ """The servers that sign in with OAuth, in config order."""
369
+ return [name for name, server in self.config.servers.items() if server.auth is not None]
370
+
371
+ def login_command(self, server: str) -> str:
372
+ """The command that signs in to a server; it names the server only when the bin has several to sign in to."""
373
+ several = len([name for name, config in self.loaded.config.servers.items() if config.auth is not None]) > 1
374
+ return f"{self.app.bin_name} auth login" + (f" {server}" if several else "")
375
+
347
376
  def close(self) -> None:
348
377
  for client in self.clients.values():
349
378
  client.close()
@@ -367,10 +396,12 @@ class Runtime:
367
396
  self._live.add(server)
368
397
  try:
369
398
  tools = client.list_tools()
370
- except (TransportError, ServerRejectedError, ConfigError) as error:
399
+ except (TransportError, ServerRejectedError, ConfigError, AuthError) as error:
371
400
  if fallback is None:
372
401
  if isinstance(error, ConfigError):
373
402
  raise UnresolvedServer(str(error)) from error
403
+ if isinstance(error, AuthError):
404
+ raise AuthFailure(f"cannot list the tools of {server}: {error}") from error
374
405
  raise TransportFailure(f"cannot list the tools of {client.display_url} ({server}): {error}") from error
375
406
  click.echo(
376
407
  f"{self.app.bin_name}: warning: cannot refresh the tool list of {server} ({error}); "
@@ -509,13 +540,13 @@ class Runtime:
509
540
  found[server] = replace(entry, command=prefix + entry.command)
510
541
 
511
542
  to_ask = unknown if found else candidates
512
- unchecked: list[tuple[str, TransportFailure | UnresolvedServer]] = []
543
+ unchecked: list[tuple[str, TransportFailure | UnresolvedServer | AuthFailure]] = []
513
544
  for server, prefix in to_ask:
514
545
  if server in found:
515
546
  continue
516
547
  try:
517
548
  entry = self.find_in_server(server, name[len(prefix) :])
518
- except (TransportFailure, UnresolvedServer) as error:
549
+ except (TransportFailure, UnresolvedServer, AuthFailure) as error:
519
550
  unchecked.append((server, error))
520
551
  continue
521
552
  if entry is not None:
@@ -535,6 +566,8 @@ class Runtime:
535
566
  message = "\n".join(failure.format_message() for _, failure in unchecked)
536
567
  if any(isinstance(failure, UnresolvedServer) for _, failure in unchecked):
537
568
  raise ConfigFailure(message)
569
+ if any(isinstance(failure, AuthFailure) for _, failure in unchecked):
570
+ raise AuthFailure(message)
538
571
  raise TransportFailure(message)
539
572
  return None
540
573
 
@@ -570,10 +603,12 @@ class Runtime:
570
603
  for server, prefix in self.top_level_servers():
571
604
  try:
572
605
  tools = self.server_tools(server)
573
- except (TransportFailure, UnresolvedServer) as error:
606
+ except (TransportFailure, UnresolvedServer, AuthFailure) as error:
574
607
  listing.unavailable[server] = error.format_message()
575
608
  if isinstance(error, UnresolvedServer):
576
609
  listing.unresolved.add(server)
610
+ if isinstance(error, AuthFailure):
611
+ listing.unauthenticated.add(server)
577
612
  continue
578
613
  for command, entry in tools.entries.items():
579
614
  full = prefix + command
@@ -835,7 +870,7 @@ class KitGroup(click.Group):
835
870
 
836
871
  def list_commands(self, ctx: click.Context) -> list[str]:
837
872
  listing = self._listing(ctx)
838
- return sorted([*listing.tools, *listing.groups, *BUILTIN_COMMANDS]) # schema and config
873
+ return sorted([*listing.tools, *listing.groups, *_top_level_builtins(_runtime(ctx))])
839
874
 
840
875
  def _listing(self, ctx: click.Context) -> TopLevelListing:
841
876
  runtime = _runtime(ctx)
@@ -843,7 +878,9 @@ class KitGroup(click.Group):
843
878
  if listing.unavailable and not listing.tools and not listing.groups:
844
879
  # Nothing at all to show: the failures are the answer, as an error.
845
880
  message = "\n".join(listing.unavailable.values())
846
- raise ConfigFailure(message) if listing.unresolved else TransportFailure(message)
881
+ if listing.unresolved:
882
+ raise ConfigFailure(message)
883
+ raise AuthFailure(message) if listing.unauthenticated else TransportFailure(message)
847
884
  return listing
848
885
 
849
886
  def get_command(self, ctx: click.Context, cmd_name: str) -> click.Command | None:
@@ -851,6 +888,8 @@ class KitGroup(click.Group):
851
888
  return SchemaCommand()
852
889
  if cmd_name == ConfigCommand.NAME:
853
890
  return ConfigCommand()
891
+ if cmd_name == AuthGroup.NAME:
892
+ return AuthGroup()
854
893
  runtime = _runtime(ctx)
855
894
  groups = runtime.group_mounts()
856
895
  if cmd_name in groups:
@@ -879,7 +918,7 @@ class KitGroup(click.Group):
879
918
  if rows:
880
919
  with formatter.section("Tools"):
881
920
  formatter.write_dl(rows)
882
- _write_builtins(formatter, top_level=True)
921
+ _write_builtins(formatter, top_level=True, auth=bool(_runtime(ctx).oauth_servers()))
883
922
  if listing.unavailable:
884
923
  with formatter.section("Unavailable servers"):
885
924
  formatter.write_dl(sorted(listing.unavailable.items()))
@@ -996,10 +1035,17 @@ class SchemaCommand(click.Command):
996
1035
  _write(json.dumps(schema, ensure_ascii=False, indent=indent) + "\n", "stdout")
997
1036
 
998
1037
 
999
- def _write_builtins(formatter: click.HelpFormatter, *, top_level: bool = False) -> None:
1038
+ def _top_level_builtins(runtime: Runtime) -> list[str]:
1039
+ """The built-in commands at the top level; ``auth`` only when a server signs in with OAuth."""
1040
+ return [name for name in BUILTIN_COMMANDS if name != AuthGroup.NAME or runtime.oauth_servers()]
1041
+
1042
+
1043
+ def _write_builtins(formatter: click.HelpFormatter, *, top_level: bool = False, auth: bool = False) -> None:
1000
1044
  rows = [(SchemaCommand.NAME, SchemaCommand.HELP)]
1001
1045
  if top_level:
1002
1046
  rows.append((ConfigCommand.NAME, ConfigCommand.HELP))
1047
+ if auth:
1048
+ rows.append((AuthGroup.NAME, AuthGroup.HELP))
1003
1049
  with formatter.section("Commands"):
1004
1050
  formatter.write_dl(sorted(rows))
1005
1051
 
@@ -1059,6 +1105,178 @@ class ConfigCommand(click.Command):
1059
1105
  _write(json.dumps(config_view.describe(loaded), ensure_ascii=False, indent=indent) + "\n", "stdout")
1060
1106
 
1061
1107
 
1108
+ class AuthGroup(click.Group):
1109
+ """``auth``: sign in to the servers that use OAuth, sign out, and show who is signed in.
1110
+
1111
+ Signing in is only ever done here. A tool command never opens a browser: without a usable
1112
+ sign-in it exits with ``EXIT_AUTH``, so an AI agent gets an answer at once instead of a
1113
+ command that waits for a person.
1114
+ """
1115
+
1116
+ NAME = "auth"
1117
+ HELP = "Sign in to the servers that use OAuth, sign out, or show the sign-in state."
1118
+
1119
+ def __init__(self) -> None:
1120
+ super().__init__(name=self.NAME, help=self.HELP, no_args_is_help=True)
1121
+ server = click.Argument(["server"], required=False, metavar="[SERVER]")
1122
+ self.add_command(
1123
+ click.Command(
1124
+ "login",
1125
+ callback=_login,
1126
+ help=(
1127
+ "Sign in to a server through the browser and store its tokens. Without SERVER, sign in to every "
1128
+ "server that uses OAuth. The sign-in address is also printed, to open by hand. Commands refresh "
1129
+ "the tokens by themselves afterwards, until the authorization server ends the sign-in."
1130
+ ),
1131
+ params=[
1132
+ server,
1133
+ click.Option(
1134
+ ["--no-browser"],
1135
+ is_flag=True,
1136
+ help="Only print the sign-in address; do not open a browser.",
1137
+ ),
1138
+ click.Option(
1139
+ ["--timeout"],
1140
+ type=click.FloatRange(min=1),
1141
+ default=oauth.DEFAULT_LOGIN_TIMEOUT_SECONDS,
1142
+ show_default=True,
1143
+ help="Seconds to wait for the sign-in in the browser.",
1144
+ ),
1145
+ ],
1146
+ )
1147
+ )
1148
+ self.add_command(
1149
+ click.Command(
1150
+ "logout",
1151
+ callback=_logout,
1152
+ help=(
1153
+ "Delete the stored tokens of a server, or of every server that uses OAuth. With --revoke, also "
1154
+ "revoke the sign-in at the authorization server. Google revokes it for every app that uses the "
1155
+ "same OAuth client, so other tools signed in with that client are signed out too."
1156
+ ),
1157
+ params=[
1158
+ click.Argument(["server"], required=False, metavar="[SERVER]"),
1159
+ click.Option(
1160
+ ["--revoke"], is_flag=True, help="Also revoke the sign-in at the authorization server."
1161
+ ),
1162
+ ],
1163
+ )
1164
+ )
1165
+ self.add_command(
1166
+ click.Command(
1167
+ "status",
1168
+ callback=_status,
1169
+ help=(
1170
+ "Print the sign-in state of each server that uses OAuth as JSON, without the tokens. Nothing is "
1171
+ "sent to any server. Exits 4 when a server is not signed in."
1172
+ ),
1173
+ params=[click.Argument(["server"], required=False, metavar="[SERVER]"), *_mode_options()],
1174
+ )
1175
+ )
1176
+
1177
+
1178
+ def _oauth_targets(server: str | None) -> tuple[Runtime, list[str]]:
1179
+ ctx = click.get_current_context()
1180
+ runtime = _runtime(ctx)
1181
+ names = runtime.oauth_servers()
1182
+ if server is None:
1183
+ if not names:
1184
+ raise click.UsageError("No configured server signs in with OAuth.", ctx)
1185
+ return runtime, names
1186
+ if server not in runtime.config.servers:
1187
+ raise click.UsageError(f"No server named {server!r}. Servers: {', '.join(runtime.config.servers)}.", ctx)
1188
+ if server not in names:
1189
+ raise click.UsageError(f"The server {server!r} does not sign in with OAuth (it has no auth key).", ctx)
1190
+ return runtime, [server]
1191
+
1192
+
1193
+ def _resolved(runtime: Runtime, name: str) -> ResolvedServer:
1194
+ try:
1195
+ resolved = runtime.clients[name].resolve()
1196
+ except ConfigError as error:
1197
+ raise ConfigFailure(str(error)) from error
1198
+ assert resolved.auth is not None
1199
+ return resolved
1200
+
1201
+
1202
+ def _login(server: str | None, no_browser: bool, timeout: float) -> None:
1203
+ runtime, names = _oauth_targets(server)
1204
+ for name in names:
1205
+ resolved = _resolved(runtime, name)
1206
+ assert resolved.auth is not None
1207
+ try:
1208
+ tokens = oauth.login(
1209
+ name,
1210
+ resolved.url,
1211
+ resolved.auth,
1212
+ runtime.tokens,
1213
+ echo=lambda line: click.echo(line, err=True),
1214
+ browser=not no_browser,
1215
+ wait_timeout=timeout,
1216
+ http_timeout=runtime.config.servers[name].timeout,
1217
+ )
1218
+ except AuthError as error:
1219
+ raise AuthFailure(f"signing in to {name} failed: {error}") from error
1220
+ except AuthTransportError as error:
1221
+ raise TransportFailure(f"signing in to {name} failed: {error}") from error
1222
+ who = f" as {tokens.identity}" if tokens.identity else ""
1223
+ click.echo(f"Signed in to {name}{who}.", err=True)
1224
+
1225
+
1226
+ def _logout(server: str | None, revoke: bool) -> None:
1227
+ runtime, names = _oauth_targets(server)
1228
+ for name in names:
1229
+ tokens = runtime.tokens.load(name)
1230
+ if tokens is None:
1231
+ click.echo(f"Not signed in to {name}.", err=True)
1232
+ continue
1233
+ if revoke:
1234
+ resolved = _resolved(runtime, name)
1235
+ assert resolved.auth is not None
1236
+ try:
1237
+ if not oauth.revoke(tokens, resolved.auth, runtime.config.servers[name].timeout):
1238
+ click.echo(f"The authorization server of {name} offers no revocation; only signing out.", err=True)
1239
+ except AuthError as error:
1240
+ raise AuthFailure(f"revoking the sign-in to {name} failed: {error}") from error
1241
+ except AuthTransportError as error:
1242
+ raise TransportFailure(f"revoking the sign-in to {name} failed: {error}") from error
1243
+ runtime.tokens.delete(name)
1244
+ click.echo(f"Signed out of {name}.", err=True)
1245
+
1246
+
1247
+ def _status(server: str | None, machine_output: bool, pretty_output: bool) -> None:
1248
+ ctx = click.get_current_context()
1249
+ runtime, names = _oauth_targets(server)
1250
+ servers = []
1251
+ for name in names:
1252
+ resolved = _resolved(runtime, name)
1253
+ assert resolved.auth is not None
1254
+ kind = resolved.auth.config.bearer
1255
+ stored = runtime.tokens.load(name)
1256
+ tokens = stored if stored is not None and stored.is_for(resolved.url, resolved.auth) else None
1257
+ expiry = tokens.expiry(kind) if tokens is not None else None
1258
+ servers.append(
1259
+ {
1260
+ "server": name,
1261
+ "signed_in": tokens is not None and (tokens.is_fresh(kind) or tokens.refresh_token is not None),
1262
+ "identity": tokens.identity if tokens is not None else None,
1263
+ "bearer": kind,
1264
+ "expires_at": _iso_time(expiry) if expiry is not None else None,
1265
+ "refreshable": tokens is not None and tokens.refresh_token is not None,
1266
+ "scopes": tokens.scope.split() if tokens is not None and tokens.scope else [],
1267
+ "token_file": str(runtime.tokens.path(name)),
1268
+ }
1269
+ )
1270
+ mode = resolve_mode(*_modes(ctx))
1271
+ _write(json.dumps({"servers": servers}, indent=2 if mode == "pretty" else None) + "\n", "stdout")
1272
+ if not all(entry["signed_in"] for entry in servers):
1273
+ ctx.exit(EXIT_AUTH)
1274
+
1275
+
1276
+ def _iso_time(epoch: float) -> str:
1277
+ return datetime.fromtimestamp(epoch, tz=UTC).isoformat(timespec="seconds")
1278
+
1279
+
1062
1280
  class ToolCommand(click.Command):
1063
1281
  """One tool as a command; its options are compiled from the tool's input schema."""
1064
1282
 
@@ -1104,6 +1322,8 @@ class ToolCommand(click.Command):
1104
1322
  result = client.call_tool(self.entry.name, arguments)
1105
1323
  except ConfigError as error:
1106
1324
  raise ConfigFailure(str(error)) from error
1325
+ except AuthError as error:
1326
+ raise AuthFailure(str(error)) from error
1107
1327
  except TransportError as error:
1108
1328
  raise TransportFailure(str(error)) from error
1109
1329
  except ServerRejectedError as error: