askfirst 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- askfirst-0.1.0/.gitignore +12 -0
- askfirst-0.1.0/CHANGELOG.md +17 -0
- askfirst-0.1.0/LICENSE +21 -0
- askfirst-0.1.0/PKG-INFO +160 -0
- askfirst-0.1.0/README.md +132 -0
- askfirst-0.1.0/pyproject.toml +43 -0
- askfirst-0.1.0/src/askfirst/__init__.py +34 -0
- askfirst-0.1.0/src/askfirst/confirm.py +235 -0
- askfirst-0.1.0/src/askfirst/errors.py +62 -0
- askfirst-0.1.0/src/askfirst/restrict.py +146 -0
- askfirst-0.1.0/src/askfirst/tokens.py +138 -0
- askfirst-0.1.0/tests/test_confirm.py +192 -0
- askfirst-0.1.0/tests/test_restrict.py +153 -0
- askfirst-0.1.0/tests/test_sdk.py +175 -0
- askfirst-0.1.0/tests/test_tokens.py +111 -0
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## 0.1.0 (2026-11-09)
|
|
4
|
+
|
|
5
|
+
First release.
|
|
6
|
+
|
|
7
|
+
- `Confirmer` / `confirm`: one `await` at the top of a destructive tool. Shows a yes/no
|
|
8
|
+
elicitation prompt when the client supports it; otherwise (or when the prompt cannot be sent,
|
|
9
|
+
e.g. no back-channel) asks the model to check with the user and call again with a signed,
|
|
10
|
+
single-use token bound to the action, the arguments and an optional subject.
|
|
11
|
+
Modes `auto`, `elicit` (refuse without a prompt) and `token`; answer `timeout`.
|
|
12
|
+
- Declined, cancelled, unchecked and timed-out prompts all stop the call.
|
|
13
|
+
- Errors subclass the MCP SDK's `ToolError`, so the model sees their text on SDK 1.x and 2.x.
|
|
14
|
+
- `restrict` / `restrict_from_env`: read-only mode (keeps only `readOnlyHint=True` tools,
|
|
15
|
+
unannotated tools count as writes) and glob allow/deny lists. Removed tools cannot be called
|
|
16
|
+
by name; a pattern that matches nothing is an error.
|
|
17
|
+
- Tested against MCP Python SDK 1.10, 1.x latest and 2.x, including the 2026-07-28 protocol.
|
askfirst-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Sri Krishna Lingamaneni
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
askfirst-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: askfirst
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Confirm destructive MCP tool calls with the user (elicitation, with a signed-token fallback for clients without it) and add a read-only mode to Python MCP servers
|
|
5
|
+
Project-URL: Homepage, https://github.com/srikrishnaL/kitforge/tree/main/packages/askfirst
|
|
6
|
+
Project-URL: Source, https://github.com/srikrishnaL/kitforge
|
|
7
|
+
Project-URL: Issues, https://github.com/srikrishnaL/kitforge/issues
|
|
8
|
+
Project-URL: Changelog, https://github.com/srikrishnaL/kitforge/blob/main/packages/askfirst/CHANGELOG.md
|
|
9
|
+
Author: Sri Krishna Lingamaneni
|
|
10
|
+
License-Expression: MIT
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Keywords: confirmation,destructive tools,elicitation,fastmcp,human in the loop,mcp,mcp server,model context protocol,read-only mode,tool filtering
|
|
13
|
+
Classifier: Development Status :: 4 - Beta
|
|
14
|
+
Classifier: Intended Audience :: Developers
|
|
15
|
+
Classifier: Operating System :: OS Independent
|
|
16
|
+
Classifier: Programming Language :: Python :: 3
|
|
17
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
18
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
19
|
+
Classifier: Topic :: Security
|
|
20
|
+
Classifier: Topic :: Software Development :: Libraries
|
|
21
|
+
Requires-Python: >=3.9
|
|
22
|
+
Provides-Extra: test
|
|
23
|
+
Requires-Dist: anyio>=4; extra == 'test'
|
|
24
|
+
Requires-Dist: mcp>=1.10; (python_version >= '3.10') and extra == 'test'
|
|
25
|
+
Requires-Dist: pydantic>=2; extra == 'test'
|
|
26
|
+
Requires-Dist: pytest>=7; extra == 'test'
|
|
27
|
+
Description-Content-Type: text/markdown
|
|
28
|
+
|
|
29
|
+
# askfirst
|
|
30
|
+
|
|
31
|
+
Ask the user before an MCP tool deletes, sends or pays for anything, on every client.
|
|
32
|
+
|
|
33
|
+
MCP servers are meant to confirm destructive tool calls through *elicitation*, but many clients
|
|
34
|
+
don't support it, declare it and then auto-decline, or (on stateless and 2026-07-28 connections)
|
|
35
|
+
can't receive the prompt at all, so servers either skip the check or break. askfirst is one
|
|
36
|
+
`await` that shows a yes/no prompt when the client can, and otherwise falls back to a signed,
|
|
37
|
+
single-use confirmation token bound to the exact call. It also adds a read-only mode that
|
|
38
|
+
really removes write tools.
|
|
39
|
+
|
|
40
|
+
```bash
|
|
41
|
+
pip install askfirst
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
Python 3.9+, no dependencies of its own (it uses the pydantic and anyio your MCP SDK already
|
|
45
|
+
installs). Works with the official MCP Python SDK 1.x (`FastMCP`) and 2.x
|
|
46
|
+
(`MCPServer`).
|
|
47
|
+
|
|
48
|
+
## Confirm a destructive tool
|
|
49
|
+
|
|
50
|
+
```python
|
|
51
|
+
from mcp.server.fastmcp import FastMCP, Context # SDK 2.x: from mcp.server.mcpserver import MCPServer, Context
|
|
52
|
+
from mcp.types import ToolAnnotations
|
|
53
|
+
from askfirst import Confirmer
|
|
54
|
+
|
|
55
|
+
mcp = FastMCP("git-host")
|
|
56
|
+
ask = Confirmer()
|
|
57
|
+
|
|
58
|
+
@mcp.tool(annotations=ToolAnnotations(destructiveHint=True))
|
|
59
|
+
async def delete_branch(repo: str, branch: str, ctx: Context, confirm_token: str = "") -> str:
|
|
60
|
+
"""Delete a branch. Asks the user first."""
|
|
61
|
+
await ask(ctx, f"Delete branch {branch} in {repo}? This cannot be undone.",
|
|
62
|
+
action="delete_branch", args={"repo": repo, "branch": branch}, token=confirm_token)
|
|
63
|
+
# Only reached once the user said yes.
|
|
64
|
+
return f"Deleted {branch}"
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
What happens:
|
|
68
|
+
|
|
69
|
+
| Client | First call | Then |
|
|
70
|
+
| --- | --- | --- |
|
|
71
|
+
| Supports elicitation | The user sees the message with a **Confirm** checkbox | Yes: the tool runs. No, cancel, or no answer within `timeout`: the model gets "The user declined ... Nothing was done." |
|
|
72
|
+
| No elicitation, or the prompt can't be sent | The model gets an error: "Confirmation required. This call was not run. Ask the user whether to go ahead ... call delete_branch again with exactly the same arguments plus `confirm_token="..."`" | The second call with the token runs the tool |
|
|
73
|
+
|
|
74
|
+
The token is an HMAC over the action, the arguments and an optional `subject`, valid for 5
|
|
75
|
+
minutes and only once. A token issued for `delete_branch("old")` does not work for
|
|
76
|
+
`delete_branch("main")`, an expired or reused token gets a fresh one with the reason, and on a
|
|
77
|
+
client that can show prompts a token never replaces the prompt.
|
|
78
|
+
|
|
79
|
+
The errors are the SDK's own `ToolError`, so their text reaches the model as the tool result
|
|
80
|
+
(SDK 2.x hides the text of other exceptions).
|
|
81
|
+
|
|
82
|
+
### Settings
|
|
83
|
+
|
|
84
|
+
```python
|
|
85
|
+
Confirmer(
|
|
86
|
+
secret=None, # HMAC key; default random at start-up (tokens die on restart)
|
|
87
|
+
ttl=300, # seconds a token is valid
|
|
88
|
+
mode="auto", # "auto" | "elicit" (prompt or refuse) | "token" (always two calls)
|
|
89
|
+
timeout=None, # seconds to wait for the user's answer; no answer = no
|
|
90
|
+
token_param="confirm_token",
|
|
91
|
+
store=None, # shared used-token store for multi-process servers
|
|
92
|
+
)
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
Pass `subject=` (the authenticated user id or session id) so one user's token cannot be used
|
|
96
|
+
by another. `await askfirst.confirm(ctx, ...)` is the same call with default settings.
|
|
97
|
+
|
|
98
|
+
## Read-only mode and tool allow/deny lists
|
|
99
|
+
|
|
100
|
+
```python
|
|
101
|
+
from askfirst import restrict_from_env
|
|
102
|
+
|
|
103
|
+
# ... register all tools first ...
|
|
104
|
+
restrict_from_env(mcp) # MCP_READ_ONLY=true, MCP_ALLOW_TOOLS=list_*,get_*, MCP_DENY_TOOLS=delete_*
|
|
105
|
+
mcp.run()
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
Or in code: `restrict(mcp, read_only=True, allow=["list_*"], deny=["delete_*"])`. It returns the
|
|
109
|
+
removed names.
|
|
110
|
+
|
|
111
|
+
- Tools are removed from the server, so they are gone from `tools/list` **and** calling one by
|
|
112
|
+
name fails.
|
|
113
|
+
- Read-only keeps only tools annotated `readOnlyHint=True`. A tool with no annotations counts
|
|
114
|
+
as a write tool, so a new tool someone forgot to annotate is hidden, not leaked.
|
|
115
|
+
- Deny beats allow. Patterns are case-sensitive globs, and a pattern that matches no tool is an
|
|
116
|
+
error, so a typo can't silently leave `delete_repo` exposed.
|
|
117
|
+
|
|
118
|
+
## Limits
|
|
119
|
+
|
|
120
|
+
- The token fallback trusts the model to relay the question to the user. It stops the model
|
|
121
|
+
from running a destructive call on its own initiative or with changed arguments, but a model
|
|
122
|
+
that ignores the instruction could still resend the token. For hard guarantees use
|
|
123
|
+
`mode="elicit"`, which refuses on clients that cannot prompt.
|
|
124
|
+
- On SDK 2.x connections using the 2026-07-28 protocol, prompts are carried by multi-round-trip
|
|
125
|
+
requests (`InputRequiredResult`); askfirst does not produce those yet and uses the token
|
|
126
|
+
fallback there. Native support is planned.
|
|
127
|
+
- A declined prompt is a no, even when the client declined it automatically (a known client
|
|
128
|
+
bug). That is the safe side.
|
|
129
|
+
- The used-token store is in memory. With several workers, pass a shared `store` (an object
|
|
130
|
+
with `use(nonce, expires_at) -> bool`) and a fixed `secret`.
|
|
131
|
+
- `restrict` acts on tools registered when you call it. Call it last.
|
|
132
|
+
- The standalone `fastmcp` package: `confirm` works with its `Context`; `restrict` does not (use
|
|
133
|
+
fastmcp's own tag filters there).
|
|
134
|
+
- Python only for now; the TypeScript SDK is next if people ask.
|
|
135
|
+
|
|
136
|
+
## Why this exists
|
|
137
|
+
|
|
138
|
+
Server authors keep asking for this, and building it by hand is easy to get wrong:
|
|
139
|
+
|
|
140
|
+
- [MemPalace/mempalace#1981](https://github.com/MemPalace/mempalace/issues/1981): opt-in
|
|
141
|
+
read-only MCP mode plus guarded writes with explicit user confirmation.
|
|
142
|
+
- [pulsemcp/mcp-servers#384](https://github.com/pulsemcp/mcp-servers/issues/384): an
|
|
143
|
+
elicitation fallback pattern for clients without native elicitation.
|
|
144
|
+
- [erayendes/app-store-connect-mcp#112](https://github.com/erayendes/app-store-connect-mcp/issues/112):
|
|
145
|
+
keep the write guard on clients without elicitation with a preview and a request-bound
|
|
146
|
+
confirmation token.
|
|
147
|
+
- [TojiiSamaa/netbox-mcp-rust#4](https://github.com/TojiiSamaa/netbox-mcp-rust/issues/4):
|
|
148
|
+
destructive tools run without confirmation when the client does not support elicitation.
|
|
149
|
+
- [PrefectHQ/fastmcp#4929](https://github.com/PrefectHQ/fastmcp/issues/4929): declined and
|
|
150
|
+
cancelled elicitation results are truthy, so the obvious `if await ctx.elicit(...)` guard
|
|
151
|
+
lets refused actions through.
|
|
152
|
+
- [anthropics/claude-code#98256](https://github.com/anthropics/claude-code/issues/98256): a
|
|
153
|
+
client that declares elicitation and auto-declines it, so servers can't rely on prompts alone.
|
|
154
|
+
- Read-only mode requests: [strausmann/mcp-dockhand#254](https://github.com/strausmann/mcp-dockhand/issues/254),
|
|
155
|
+
[signadot/community#122](https://github.com/signadot/community/issues/122),
|
|
156
|
+
[microsoft/azure-skills#197](https://github.com/microsoft/azure-skills/issues/197).
|
|
157
|
+
|
|
158
|
+
## License
|
|
159
|
+
|
|
160
|
+
MIT
|
askfirst-0.1.0/README.md
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
# askfirst
|
|
2
|
+
|
|
3
|
+
Ask the user before an MCP tool deletes, sends or pays for anything, on every client.
|
|
4
|
+
|
|
5
|
+
MCP servers are meant to confirm destructive tool calls through *elicitation*, but many clients
|
|
6
|
+
don't support it, declare it and then auto-decline, or (on stateless and 2026-07-28 connections)
|
|
7
|
+
can't receive the prompt at all, so servers either skip the check or break. askfirst is one
|
|
8
|
+
`await` that shows a yes/no prompt when the client can, and otherwise falls back to a signed,
|
|
9
|
+
single-use confirmation token bound to the exact call. It also adds a read-only mode that
|
|
10
|
+
really removes write tools.
|
|
11
|
+
|
|
12
|
+
```bash
|
|
13
|
+
pip install askfirst
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
Python 3.9+, no dependencies of its own (it uses the pydantic and anyio your MCP SDK already
|
|
17
|
+
installs). Works with the official MCP Python SDK 1.x (`FastMCP`) and 2.x
|
|
18
|
+
(`MCPServer`).
|
|
19
|
+
|
|
20
|
+
## Confirm a destructive tool
|
|
21
|
+
|
|
22
|
+
```python
|
|
23
|
+
from mcp.server.fastmcp import FastMCP, Context # SDK 2.x: from mcp.server.mcpserver import MCPServer, Context
|
|
24
|
+
from mcp.types import ToolAnnotations
|
|
25
|
+
from askfirst import Confirmer
|
|
26
|
+
|
|
27
|
+
mcp = FastMCP("git-host")
|
|
28
|
+
ask = Confirmer()
|
|
29
|
+
|
|
30
|
+
@mcp.tool(annotations=ToolAnnotations(destructiveHint=True))
|
|
31
|
+
async def delete_branch(repo: str, branch: str, ctx: Context, confirm_token: str = "") -> str:
|
|
32
|
+
"""Delete a branch. Asks the user first."""
|
|
33
|
+
await ask(ctx, f"Delete branch {branch} in {repo}? This cannot be undone.",
|
|
34
|
+
action="delete_branch", args={"repo": repo, "branch": branch}, token=confirm_token)
|
|
35
|
+
# Only reached once the user said yes.
|
|
36
|
+
return f"Deleted {branch}"
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
What happens:
|
|
40
|
+
|
|
41
|
+
| Client | First call | Then |
|
|
42
|
+
| --- | --- | --- |
|
|
43
|
+
| Supports elicitation | The user sees the message with a **Confirm** checkbox | Yes: the tool runs. No, cancel, or no answer within `timeout`: the model gets "The user declined ... Nothing was done." |
|
|
44
|
+
| No elicitation, or the prompt can't be sent | The model gets an error: "Confirmation required. This call was not run. Ask the user whether to go ahead ... call delete_branch again with exactly the same arguments plus `confirm_token="..."`" | The second call with the token runs the tool |
|
|
45
|
+
|
|
46
|
+
The token is an HMAC over the action, the arguments and an optional `subject`, valid for 5
|
|
47
|
+
minutes and only once. A token issued for `delete_branch("old")` does not work for
|
|
48
|
+
`delete_branch("main")`, an expired or reused token gets a fresh one with the reason, and on a
|
|
49
|
+
client that can show prompts a token never replaces the prompt.
|
|
50
|
+
|
|
51
|
+
The errors are the SDK's own `ToolError`, so their text reaches the model as the tool result
|
|
52
|
+
(SDK 2.x hides the text of other exceptions).
|
|
53
|
+
|
|
54
|
+
### Settings
|
|
55
|
+
|
|
56
|
+
```python
|
|
57
|
+
Confirmer(
|
|
58
|
+
secret=None, # HMAC key; default random at start-up (tokens die on restart)
|
|
59
|
+
ttl=300, # seconds a token is valid
|
|
60
|
+
mode="auto", # "auto" | "elicit" (prompt or refuse) | "token" (always two calls)
|
|
61
|
+
timeout=None, # seconds to wait for the user's answer; no answer = no
|
|
62
|
+
token_param="confirm_token",
|
|
63
|
+
store=None, # shared used-token store for multi-process servers
|
|
64
|
+
)
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
Pass `subject=` (the authenticated user id or session id) so one user's token cannot be used
|
|
68
|
+
by another. `await askfirst.confirm(ctx, ...)` is the same call with default settings.
|
|
69
|
+
|
|
70
|
+
## Read-only mode and tool allow/deny lists
|
|
71
|
+
|
|
72
|
+
```python
|
|
73
|
+
from askfirst import restrict_from_env
|
|
74
|
+
|
|
75
|
+
# ... register all tools first ...
|
|
76
|
+
restrict_from_env(mcp) # MCP_READ_ONLY=true, MCP_ALLOW_TOOLS=list_*,get_*, MCP_DENY_TOOLS=delete_*
|
|
77
|
+
mcp.run()
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
Or in code: `restrict(mcp, read_only=True, allow=["list_*"], deny=["delete_*"])`. It returns the
|
|
81
|
+
removed names.
|
|
82
|
+
|
|
83
|
+
- Tools are removed from the server, so they are gone from `tools/list` **and** calling one by
|
|
84
|
+
name fails.
|
|
85
|
+
- Read-only keeps only tools annotated `readOnlyHint=True`. A tool with no annotations counts
|
|
86
|
+
as a write tool, so a new tool someone forgot to annotate is hidden, not leaked.
|
|
87
|
+
- Deny beats allow. Patterns are case-sensitive globs, and a pattern that matches no tool is an
|
|
88
|
+
error, so a typo can't silently leave `delete_repo` exposed.
|
|
89
|
+
|
|
90
|
+
## Limits
|
|
91
|
+
|
|
92
|
+
- The token fallback trusts the model to relay the question to the user. It stops the model
|
|
93
|
+
from running a destructive call on its own initiative or with changed arguments, but a model
|
|
94
|
+
that ignores the instruction could still resend the token. For hard guarantees use
|
|
95
|
+
`mode="elicit"`, which refuses on clients that cannot prompt.
|
|
96
|
+
- On SDK 2.x connections using the 2026-07-28 protocol, prompts are carried by multi-round-trip
|
|
97
|
+
requests (`InputRequiredResult`); askfirst does not produce those yet and uses the token
|
|
98
|
+
fallback there. Native support is planned.
|
|
99
|
+
- A declined prompt is a no, even when the client declined it automatically (a known client
|
|
100
|
+
bug). That is the safe side.
|
|
101
|
+
- The used-token store is in memory. With several workers, pass a shared `store` (an object
|
|
102
|
+
with `use(nonce, expires_at) -> bool`) and a fixed `secret`.
|
|
103
|
+
- `restrict` acts on tools registered when you call it. Call it last.
|
|
104
|
+
- The standalone `fastmcp` package: `confirm` works with its `Context`; `restrict` does not (use
|
|
105
|
+
fastmcp's own tag filters there).
|
|
106
|
+
- Python only for now; the TypeScript SDK is next if people ask.
|
|
107
|
+
|
|
108
|
+
## Why this exists
|
|
109
|
+
|
|
110
|
+
Server authors keep asking for this, and building it by hand is easy to get wrong:
|
|
111
|
+
|
|
112
|
+
- [MemPalace/mempalace#1981](https://github.com/MemPalace/mempalace/issues/1981): opt-in
|
|
113
|
+
read-only MCP mode plus guarded writes with explicit user confirmation.
|
|
114
|
+
- [pulsemcp/mcp-servers#384](https://github.com/pulsemcp/mcp-servers/issues/384): an
|
|
115
|
+
elicitation fallback pattern for clients without native elicitation.
|
|
116
|
+
- [erayendes/app-store-connect-mcp#112](https://github.com/erayendes/app-store-connect-mcp/issues/112):
|
|
117
|
+
keep the write guard on clients without elicitation with a preview and a request-bound
|
|
118
|
+
confirmation token.
|
|
119
|
+
- [TojiiSamaa/netbox-mcp-rust#4](https://github.com/TojiiSamaa/netbox-mcp-rust/issues/4):
|
|
120
|
+
destructive tools run without confirmation when the client does not support elicitation.
|
|
121
|
+
- [PrefectHQ/fastmcp#4929](https://github.com/PrefectHQ/fastmcp/issues/4929): declined and
|
|
122
|
+
cancelled elicitation results are truthy, so the obvious `if await ctx.elicit(...)` guard
|
|
123
|
+
lets refused actions through.
|
|
124
|
+
- [anthropics/claude-code#98256](https://github.com/anthropics/claude-code/issues/98256): a
|
|
125
|
+
client that declares elicitation and auto-declines it, so servers can't rely on prompts alone.
|
|
126
|
+
- Read-only mode requests: [strausmann/mcp-dockhand#254](https://github.com/strausmann/mcp-dockhand/issues/254),
|
|
127
|
+
[signadot/community#122](https://github.com/signadot/community/issues/122),
|
|
128
|
+
[microsoft/azure-skills#197](https://github.com/microsoft/azure-skills/issues/197).
|
|
129
|
+
|
|
130
|
+
## License
|
|
131
|
+
|
|
132
|
+
MIT
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling>=1.27"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "askfirst"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Confirm destructive MCP tool calls with the user (elicitation, with a signed-token fallback for clients without it) and add a read-only mode to Python MCP servers"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "MIT"
|
|
11
|
+
license-files = ["LICENSE"]
|
|
12
|
+
requires-python = ">=3.9"
|
|
13
|
+
authors = [{ name = "Sri Krishna Lingamaneni" }]
|
|
14
|
+
keywords = [
|
|
15
|
+
"mcp", "model context protocol", "mcp server", "elicitation", "confirmation",
|
|
16
|
+
"human in the loop", "destructive tools", "read-only mode", "tool filtering", "fastmcp",
|
|
17
|
+
]
|
|
18
|
+
classifiers = [
|
|
19
|
+
"Development Status :: 4 - Beta",
|
|
20
|
+
"Intended Audience :: Developers",
|
|
21
|
+
"Operating System :: OS Independent",
|
|
22
|
+
"Programming Language :: Python :: 3",
|
|
23
|
+
"Programming Language :: Python :: 3 :: Only",
|
|
24
|
+
"Topic :: Security",
|
|
25
|
+
"Topic :: Software Development :: Libraries",
|
|
26
|
+
"Topic :: Scientific/Engineering :: Artificial Intelligence",
|
|
27
|
+
]
|
|
28
|
+
dependencies = []
|
|
29
|
+
|
|
30
|
+
[project.optional-dependencies]
|
|
31
|
+
test = ["pytest>=7", "pydantic>=2", "anyio>=4", "mcp>=1.10; python_version >= '3.10'"]
|
|
32
|
+
|
|
33
|
+
[project.urls]
|
|
34
|
+
Homepage = "https://github.com/srikrishnaL/kitforge/tree/main/packages/askfirst"
|
|
35
|
+
Source = "https://github.com/srikrishnaL/kitforge"
|
|
36
|
+
Issues = "https://github.com/srikrishnaL/kitforge/issues"
|
|
37
|
+
Changelog = "https://github.com/srikrishnaL/kitforge/blob/main/packages/askfirst/CHANGELOG.md"
|
|
38
|
+
|
|
39
|
+
[tool.hatch.build.targets.wheel]
|
|
40
|
+
packages = ["src/askfirst"]
|
|
41
|
+
|
|
42
|
+
[tool.pytest.ini_options]
|
|
43
|
+
testpaths = ["tests"]
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
"""askfirst: confirm destructive MCP tool calls with the user, and read-only mode.
|
|
2
|
+
|
|
3
|
+
from askfirst import Confirmer
|
|
4
|
+
|
|
5
|
+
ask = Confirmer()
|
|
6
|
+
|
|
7
|
+
@mcp.tool(annotations=ToolAnnotations(destructiveHint=True))
|
|
8
|
+
async def delete_branch(repo: str, branch: str, ctx: Context, confirm_token: str = "") -> str:
|
|
9
|
+
await ask(ctx, f"Delete branch {branch} in {repo}?", action="delete_branch",
|
|
10
|
+
args={"repo": repo, "branch": branch}, token=confirm_token)
|
|
11
|
+
...
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from .confirm import Confirmer, client_supports_elicitation, confirm
|
|
15
|
+
from .errors import AskFirstError, ConfirmationRequired, ConfirmationUnavailable, Declined
|
|
16
|
+
from .restrict import is_read_only, restrict, restrict_from_env
|
|
17
|
+
from .tokens import MemoryNonceStore, TokenSigner
|
|
18
|
+
|
|
19
|
+
__version__ = "0.1.0"
|
|
20
|
+
|
|
21
|
+
__all__ = [
|
|
22
|
+
"Confirmer",
|
|
23
|
+
"confirm",
|
|
24
|
+
"client_supports_elicitation",
|
|
25
|
+
"restrict",
|
|
26
|
+
"restrict_from_env",
|
|
27
|
+
"is_read_only",
|
|
28
|
+
"AskFirstError",
|
|
29
|
+
"ConfirmationRequired",
|
|
30
|
+
"Declined",
|
|
31
|
+
"ConfirmationUnavailable",
|
|
32
|
+
"TokenSigner",
|
|
33
|
+
"MemoryNonceStore",
|
|
34
|
+
]
|
|
@@ -0,0 +1,235 @@
|
|
|
1
|
+
"""Ask the user before a tool does something destructive.
|
|
2
|
+
|
|
3
|
+
``Confirmer.__call__`` is awaited at the top of a tool body. It returns when the
|
|
4
|
+
user has agreed and raises otherwise:
|
|
5
|
+
|
|
6
|
+
1. If the client supports elicitation, it shows a yes/no prompt to the user.
|
|
7
|
+
Yes returns; no, cancel or no answer in time raises ``Declined``.
|
|
8
|
+
2. If it does not (or the prompt cannot be sent), it raises
|
|
9
|
+
``ConfirmationRequired``. Its message asks the model to check with the user
|
|
10
|
+
and call the tool again with the same arguments and a signed, single-use
|
|
11
|
+
token. That second call returns.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import logging
|
|
17
|
+
from typing import Any, Callable, Dict, Mapping, Optional
|
|
18
|
+
|
|
19
|
+
from .errors import ConfirmationRequired, ConfirmationUnavailable, Declined
|
|
20
|
+
from .tokens import TokenSigner
|
|
21
|
+
|
|
22
|
+
__all__ = ["Confirmer", "confirm", "client_supports_elicitation"]
|
|
23
|
+
|
|
24
|
+
log = logging.getLogger("askfirst")
|
|
25
|
+
|
|
26
|
+
_MODES = ("auto", "elicit", "token")
|
|
27
|
+
_schema_cache: Dict[str, Any] = {}
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def client_supports_elicitation(ctx: Any) -> bool:
|
|
31
|
+
"""True if the connected client declared the elicitation capability.
|
|
32
|
+
|
|
33
|
+
Works with the MCP Python SDK 1.x ``FastMCP`` context, the 2.x ``MCPServer``
|
|
34
|
+
context, and the standalone ``fastmcp`` package's context.
|
|
35
|
+
"""
|
|
36
|
+
if ctx is None:
|
|
37
|
+
return False
|
|
38
|
+
caps = None
|
|
39
|
+
try:
|
|
40
|
+
caps = ctx.client_capabilities # SDK 2.x
|
|
41
|
+
except Exception:
|
|
42
|
+
caps = None
|
|
43
|
+
if caps is None:
|
|
44
|
+
try:
|
|
45
|
+
params = ctx.session.client_params # SDK 1.x, fastmcp
|
|
46
|
+
caps = params.capabilities if params is not None else None
|
|
47
|
+
except Exception:
|
|
48
|
+
caps = None
|
|
49
|
+
return getattr(caps, "elicitation", None) is not None
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _confirm_schema() -> Any:
|
|
53
|
+
"""A one-field pydantic model: ``confirm: bool`` (pydantic ships with the SDK)."""
|
|
54
|
+
model = _schema_cache.get("model")
|
|
55
|
+
if model is None:
|
|
56
|
+
from pydantic import BaseModel, Field
|
|
57
|
+
|
|
58
|
+
class Confirmation(BaseModel):
|
|
59
|
+
confirm: bool = Field(title="Confirm", description="Check to go ahead.")
|
|
60
|
+
|
|
61
|
+
model = _schema_cache["model"] = Confirmation
|
|
62
|
+
return model
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
class Confirmer:
|
|
66
|
+
"""Confirmation settings shared by your tools. Create one per server.
|
|
67
|
+
|
|
68
|
+
Args:
|
|
69
|
+
secret: HMAC key for confirmation tokens. Default: random at start-up.
|
|
70
|
+
ttl: Seconds a confirmation token stays valid (default 300).
|
|
71
|
+
mode: ``"auto"`` (prompt if the client can, else token), ``"elicit"``
|
|
72
|
+
(prompt only; refuse on clients that cannot prompt) or ``"token"``
|
|
73
|
+
(always use the two-call token flow).
|
|
74
|
+
timeout: Seconds to wait for the user to answer a prompt. ``None`` waits
|
|
75
|
+
as long as the client does. No answer in time counts as no.
|
|
76
|
+
token_param: Name of the tool parameter that receives the token. Only
|
|
77
|
+
used in the message to the model.
|
|
78
|
+
store: Shared used-token store for multi-process servers (see
|
|
79
|
+
``MemoryNonceStore``).
|
|
80
|
+
"""
|
|
81
|
+
|
|
82
|
+
def __init__(
|
|
83
|
+
self,
|
|
84
|
+
secret: Optional[bytes] = None,
|
|
85
|
+
*,
|
|
86
|
+
ttl: int = 300,
|
|
87
|
+
mode: str = "auto",
|
|
88
|
+
timeout: Optional[float] = None,
|
|
89
|
+
token_param: str = "confirm_token",
|
|
90
|
+
store: Optional[Any] = None,
|
|
91
|
+
clock: Optional[Callable[[], float]] = None,
|
|
92
|
+
):
|
|
93
|
+
if mode not in _MODES:
|
|
94
|
+
raise ValueError(f"mode must be one of {_MODES}, not {mode!r}")
|
|
95
|
+
kwargs: Dict[str, Any] = {"ttl": ttl, "store": store}
|
|
96
|
+
if clock is not None:
|
|
97
|
+
kwargs["clock"] = clock
|
|
98
|
+
self.signer = TokenSigner(secret, **kwargs)
|
|
99
|
+
self.mode = mode
|
|
100
|
+
self.timeout = timeout
|
|
101
|
+
self.token_param = token_param
|
|
102
|
+
|
|
103
|
+
async def __call__(
|
|
104
|
+
self,
|
|
105
|
+
ctx: Any,
|
|
106
|
+
message: str,
|
|
107
|
+
*,
|
|
108
|
+
action: str,
|
|
109
|
+
args: Optional[Mapping[str, Any]] = None,
|
|
110
|
+
token: Optional[str] = None,
|
|
111
|
+
subject: str = "",
|
|
112
|
+
) -> str:
|
|
113
|
+
"""Return once the user has confirmed ``message``; raise otherwise.
|
|
114
|
+
|
|
115
|
+
Args:
|
|
116
|
+
ctx: The tool's MCP ``Context`` (``None`` outside a request).
|
|
117
|
+
message: What will happen, in words the user understands, e.g.
|
|
118
|
+
``"Delete branch release/2.1 in acme/api? This cannot be undone."``
|
|
119
|
+
action: The tool name. Tokens only work for this action.
|
|
120
|
+
args: The arguments that decide what happens. Tokens only work for
|
|
121
|
+
the same arguments, so a model cannot get a token for a harmless
|
|
122
|
+
call and use it on another.
|
|
123
|
+
token: The value of the tool's token parameter (``None`` or ``""``
|
|
124
|
+
on a first call).
|
|
125
|
+
subject: Who is asking, e.g. the authenticated user id, so one
|
|
126
|
+
user's token does not work for another.
|
|
127
|
+
|
|
128
|
+
Returns:
|
|
129
|
+
``"elicitation"`` or ``"token"``: how the user confirmed.
|
|
130
|
+
"""
|
|
131
|
+
if not action:
|
|
132
|
+
raise ValueError("action is required")
|
|
133
|
+
if self.mode != "token" and client_supports_elicitation(ctx):
|
|
134
|
+
outcome = await self._elicit(ctx, message)
|
|
135
|
+
if outcome is not None:
|
|
136
|
+
return outcome
|
|
137
|
+
# The prompt could not be sent; fall through to the token flow.
|
|
138
|
+
elif self.mode == "elicit":
|
|
139
|
+
raise ConfirmationUnavailable(
|
|
140
|
+
f"This action needs the user's confirmation, and this client cannot ask for it: "
|
|
141
|
+
f"{message} Tell the user to run it from a client that supports MCP elicitation."
|
|
142
|
+
)
|
|
143
|
+
if self.mode == "elicit":
|
|
144
|
+
raise ConfirmationUnavailable(
|
|
145
|
+
f"This action needs the user's confirmation, and the prompt could not be shown: "
|
|
146
|
+
f"{message}"
|
|
147
|
+
)
|
|
148
|
+
return self._token_flow(message, action, args, token, subject)
|
|
149
|
+
|
|
150
|
+
async def _elicit(self, ctx: Any, message: str) -> Optional[str]:
|
|
151
|
+
schema = _confirm_schema()
|
|
152
|
+
try:
|
|
153
|
+
if self.timeout is not None:
|
|
154
|
+
import anyio
|
|
155
|
+
|
|
156
|
+
with anyio.fail_after(self.timeout):
|
|
157
|
+
result = await ctx.elicit(message, schema)
|
|
158
|
+
else:
|
|
159
|
+
result = await ctx.elicit(message, schema)
|
|
160
|
+
except TimeoutError:
|
|
161
|
+
raise Declined(
|
|
162
|
+
f"The user did not answer the confirmation prompt in time: {message} "
|
|
163
|
+
"Nothing was done.",
|
|
164
|
+
action="timeout",
|
|
165
|
+
) from None
|
|
166
|
+
except Exception as exc:
|
|
167
|
+
# No back-channel (stateless or 2026-07-28 connections), the client
|
|
168
|
+
# rejected the method, a transport error: the user saw nothing.
|
|
169
|
+
log.info("askfirst: elicitation failed (%s: %s); using a confirmation token",
|
|
170
|
+
type(exc).__name__, exc)
|
|
171
|
+
return None
|
|
172
|
+
action = getattr(result, "action", None)
|
|
173
|
+
if action == "accept":
|
|
174
|
+
data = getattr(result, "data", None)
|
|
175
|
+
if getattr(data, "confirm", False) is True:
|
|
176
|
+
return "elicitation"
|
|
177
|
+
raise Declined(f"The user did not confirm: {message} Nothing was done.")
|
|
178
|
+
if action == "cancel":
|
|
179
|
+
raise Declined(
|
|
180
|
+
f"The user dismissed the confirmation prompt: {message} Nothing was done.",
|
|
181
|
+
action="cancel",
|
|
182
|
+
)
|
|
183
|
+
raise Declined(
|
|
184
|
+
f"The user declined: {message} Nothing was done. Do not retry unless the user asks again."
|
|
185
|
+
)
|
|
186
|
+
|
|
187
|
+
def _token_flow(
|
|
188
|
+
self,
|
|
189
|
+
message: str,
|
|
190
|
+
action: str,
|
|
191
|
+
args: Optional[Mapping[str, Any]],
|
|
192
|
+
token: Optional[str],
|
|
193
|
+
subject: str,
|
|
194
|
+
) -> str:
|
|
195
|
+
reason = None
|
|
196
|
+
if token:
|
|
197
|
+
reason = self.signer.check(token, action, args, subject)
|
|
198
|
+
if reason is None:
|
|
199
|
+
return "token"
|
|
200
|
+
fresh = self.signer.issue(action, args, subject)
|
|
201
|
+
why = {
|
|
202
|
+
None: "",
|
|
203
|
+
"expired": "The confirmation token you sent has expired. ",
|
|
204
|
+
"used": "The confirmation token you sent was already used. ",
|
|
205
|
+
"mismatch": "The confirmation token you sent was issued for a different call. ",
|
|
206
|
+
"malformed": "The confirmation token you sent is not valid. ",
|
|
207
|
+
}[reason]
|
|
208
|
+
text = (
|
|
209
|
+
f"{why}Confirmation required. This call was not run.\n"
|
|
210
|
+
f"Action: {message}\n"
|
|
211
|
+
f"Ask the user whether to go ahead, quoting the action above. Only if they clearly say yes, "
|
|
212
|
+
f"call {action} again with exactly the same arguments plus "
|
|
213
|
+
f'{self.token_param}="{fresh}". '
|
|
214
|
+
f"The token works once, for this exact call, for {self.signer.ttl} seconds."
|
|
215
|
+
)
|
|
216
|
+
raise ConfirmationRequired(text, token=fresh, expires_in=self.signer.ttl, reason=reason)
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
_default: Optional[Confirmer] = None
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
async def confirm(
|
|
223
|
+
ctx: Any,
|
|
224
|
+
message: str,
|
|
225
|
+
*,
|
|
226
|
+
action: str,
|
|
227
|
+
args: Optional[Mapping[str, Any]] = None,
|
|
228
|
+
token: Optional[str] = None,
|
|
229
|
+
subject: str = "",
|
|
230
|
+
) -> str:
|
|
231
|
+
"""``Confirmer()(...)`` with default settings, shared by the whole process."""
|
|
232
|
+
global _default
|
|
233
|
+
if _default is None:
|
|
234
|
+
_default = Confirmer()
|
|
235
|
+
return await _default(ctx, message, action=action, args=args, token=token, subject=subject)
|