askfirst 0.1.0__tar.gz → 0.2.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.
@@ -1,5 +1,13 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.2.0 (2026-12-03)
4
+
5
+ - `Confirmer.resolve(message, action=...)`: the confirmation as an SDK 2.x resolver parameter,
6
+ `Annotated[str, ask.resolve("Delete {branch}?", action="delete_branch")]`. On 2026-07-28
7
+ connections the prompt now reaches the user through `InputRequiredResult` instead of falling
8
+ back to the token; older connections and clients without elicitation behave as before.
9
+ The message is a template over the tool arguments, and the token is bound to the ones it names.
10
+
3
11
  ## 0.1.0 (2026-11-09)
4
12
 
5
13
  First release.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: askfirst
3
- Version: 0.1.0
3
+ Version: 0.2.0
4
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
5
  Project-URL: Homepage, https://github.com/srikrishnaL/kitforge/tree/main/packages/askfirst
6
6
  Project-URL: Source, https://github.com/srikrishnaL/kitforge
@@ -79,6 +79,36 @@ client that can show prompts a token never replaces the prompt.
79
79
  The errors are the SDK's own `ToolError`, so their text reaches the model as the tool result
80
80
  (SDK 2.x hides the text of other exceptions).
81
81
 
82
+ ### Prompts on 2026-07-28 connections (SDK 2.x)
83
+
84
+ The 2026-07-28 protocol has no back-channel, so `await ask(ctx, ...)` cannot send a prompt
85
+ there and uses the token. With the MCP Python SDK 2.x, declare the confirmation as a resolver
86
+ parameter instead. The SDK then sends the prompt inside the `tools/call` result
87
+ (`InputRequiredResult`) and runs the body only after the client retries with the answer:
88
+
89
+ ```python
90
+ from typing import Annotated
91
+
92
+ @mcp.tool(annotations=ToolAnnotations(destructiveHint=True))
93
+ async def delete_branch(
94
+ repo: str,
95
+ branch: str,
96
+ confirmed: Annotated[str, ask.resolve("Delete branch {branch} in {repo}? This cannot be undone.",
97
+ action="delete_branch")],
98
+ confirm_token: str = "",
99
+ ) -> str:
100
+ # Only reached once the user said yes. `confirmed` is "elicitation" or "token".
101
+ return f"Deleted {branch}"
102
+ ```
103
+
104
+ - The message is a `str.format` template over the tool's arguments, and the token is bound to
105
+ the arguments it names (or pass `args=["repo", "branch"]`, or a function as the message).
106
+ - It behaves like `await ask(...)` everywhere else: a normal prompt on older connections, the
107
+ token on clients without elicitation, and the same "Nothing was done" errors on no or cancel.
108
+ - `confirmed` is not part of the tool's input schema; the model only sees `confirm_token`. A
109
+ name in the template that is not a tool argument fails when the tool is registered.
110
+ - `subject=lambda ctx: ...` binds tokens to a user, like `subject=` on `ask(...)`.
111
+
82
112
  ### Settings
83
113
 
84
114
  ```python
@@ -121,9 +151,9 @@ removed names.
121
151
  from running a destructive call on its own initiative or with changed arguments, but a model
122
152
  that ignores the instruction could still resend the token. For hard guarantees use
123
153
  `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.
154
+ - On 2026-07-28 connections only `ask.resolve(...)` (SDK 2.x) can show a prompt; the
155
+ `await ask(ctx, ...)` form uses the token there. `timeout` does not apply to `ask.resolve`
156
+ on those connections, because the client answers on its own retry.
127
157
  - A declined prompt is a no, even when the client declined it automatically (a known client
128
158
  bug). That is the safe side.
129
159
  - The used-token store is in memory. With several workers, pass a shared `store` (an object
@@ -51,6 +51,36 @@ client that can show prompts a token never replaces the prompt.
51
51
  The errors are the SDK's own `ToolError`, so their text reaches the model as the tool result
52
52
  (SDK 2.x hides the text of other exceptions).
53
53
 
54
+ ### Prompts on 2026-07-28 connections (SDK 2.x)
55
+
56
+ The 2026-07-28 protocol has no back-channel, so `await ask(ctx, ...)` cannot send a prompt
57
+ there and uses the token. With the MCP Python SDK 2.x, declare the confirmation as a resolver
58
+ parameter instead. The SDK then sends the prompt inside the `tools/call` result
59
+ (`InputRequiredResult`) and runs the body only after the client retries with the answer:
60
+
61
+ ```python
62
+ from typing import Annotated
63
+
64
+ @mcp.tool(annotations=ToolAnnotations(destructiveHint=True))
65
+ async def delete_branch(
66
+ repo: str,
67
+ branch: str,
68
+ confirmed: Annotated[str, ask.resolve("Delete branch {branch} in {repo}? This cannot be undone.",
69
+ action="delete_branch")],
70
+ confirm_token: str = "",
71
+ ) -> str:
72
+ # Only reached once the user said yes. `confirmed` is "elicitation" or "token".
73
+ return f"Deleted {branch}"
74
+ ```
75
+
76
+ - The message is a `str.format` template over the tool's arguments, and the token is bound to
77
+ the arguments it names (or pass `args=["repo", "branch"]`, or a function as the message).
78
+ - It behaves like `await ask(...)` everywhere else: a normal prompt on older connections, the
79
+ token on clients without elicitation, and the same "Nothing was done" errors on no or cancel.
80
+ - `confirmed` is not part of the tool's input schema; the model only sees `confirm_token`. A
81
+ name in the template that is not a tool argument fails when the tool is registered.
82
+ - `subject=lambda ctx: ...` binds tokens to a user, like `subject=` on `ask(...)`.
83
+
54
84
  ### Settings
55
85
 
56
86
  ```python
@@ -93,9 +123,9 @@ removed names.
93
123
  from running a destructive call on its own initiative or with changed arguments, but a model
94
124
  that ignores the instruction could still resend the token. For hard guarantees use
95
125
  `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.
126
+ - On 2026-07-28 connections only `ask.resolve(...)` (SDK 2.x) can show a prompt; the
127
+ `await ask(ctx, ...)` form uses the token there. `timeout` does not apply to `ask.resolve`
128
+ on those connections, because the client answers on its own retry.
99
129
  - A declined prompt is a no, even when the client declined it automatically (a known client
100
130
  bug). That is the safe side.
101
131
  - The used-token store is in memory. With several workers, pass a shared `store` (an object
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "askfirst"
7
- version = "0.1.0"
7
+ version = "0.2.0"
8
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
9
  readme = "README.md"
10
10
  license = "MIT"
@@ -16,7 +16,7 @@ from .errors import AskFirstError, ConfirmationRequired, ConfirmationUnavailable
16
16
  from .restrict import is_read_only, restrict, restrict_from_env
17
17
  from .tokens import MemoryNonceStore, TokenSigner
18
18
 
19
- __version__ = "0.1.0"
19
+ __version__ = "0.2.0"
20
20
 
21
21
  __all__ = [
22
22
  "Confirmer",
@@ -14,7 +14,7 @@ user has agreed and raises otherwise:
14
14
  from __future__ import annotations
15
15
 
16
16
  import logging
17
- from typing import Any, Callable, Dict, Mapping, Optional
17
+ from typing import Any, Callable, Dict, Mapping, Optional, Sequence
18
18
 
19
19
  from .errors import ConfirmationRequired, ConfirmationUnavailable, Declined
20
20
  from .tokens import TokenSigner
@@ -169,20 +169,38 @@ class Confirmer:
169
169
  log.info("askfirst: elicitation failed (%s: %s); using a confirmation token",
170
170
  type(exc).__name__, exc)
171
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
- )
172
+ return interpret(getattr(result, "action", None), getattr(result, "data", None), message)
173
+
174
+ def resolve(
175
+ self,
176
+ message: Any,
177
+ *,
178
+ action: str,
179
+ args: Optional[Sequence[str]] = None,
180
+ subject: Optional[Callable[[Any], str]] = None,
181
+ ) -> Any:
182
+ """A ``Resolve(...)`` marker that confirms before the tool body runs (MCP SDK 2.x).
183
+
184
+ Use it as a tool parameter, ``ok: Annotated[str, ask.resolve(...)]``. On
185
+ 2026-07-28 connections the prompt rides the call itself (``InputRequiredResult``),
186
+ so clients that support elicitation show it with no back-channel; on older
187
+ connections it behaves like ``await ask(...)``. Either way the token fallback
188
+ still applies, so the tool needs a ``confirm_token`` parameter (``token_param``).
189
+
190
+ Args:
191
+ message: A ``str.format`` template over the tool's arguments, such as
192
+ ``"Delete branch {branch} in {repo}?"``, or a function taking those
193
+ arguments by keyword and returning the text.
194
+ action: The tool name. Tokens only work for this action.
195
+ args: Names of the tool arguments the token is bound to. Default: the
196
+ fields of the ``message`` template (required when ``message`` is a function).
197
+ subject: Optional ``subject(ctx) -> str``, e.g. the authenticated user id.
198
+
199
+ The injected value is ``"elicitation"`` or ``"token"``; a refusal raises before the body runs.
200
+ """
201
+ from .resolve import build_resolve
202
+
203
+ return build_resolve(self, message, action=action, args=args, subject=subject)
186
204
 
187
205
  def _token_flow(
188
206
  self,
@@ -216,6 +234,27 @@ class Confirmer:
216
234
  raise ConfirmationRequired(text, token=fresh, expires_in=self.signer.ttl, reason=reason)
217
235
 
218
236
 
237
+ def interpret(action: Any, data: Any, message: str) -> str:
238
+ """Turn an elicitation answer into ``"elicitation"`` or a ``Declined`` error."""
239
+ if action == "accept":
240
+ if getattr(data, "confirm", False) is True:
241
+ return "elicitation"
242
+ raise Declined(f"The user did not confirm: {message} Nothing was done.")
243
+ if action == "cancel":
244
+ raise Declined(
245
+ f"The user dismissed the confirmation prompt: {message} Nothing was done.",
246
+ action="cancel",
247
+ )
248
+ raise Declined(
249
+ f"The user declined: {message} Nothing was done. Do not retry unless the user asks again."
250
+ )
251
+
252
+
253
+ def confirmation_schema() -> Any:
254
+ """The pydantic model askfirst asks the client to fill in: ``confirm: bool``."""
255
+ return _confirm_schema()
256
+
257
+
219
258
  _default: Optional[Confirmer] = None
220
259
 
221
260
 
@@ -0,0 +1,147 @@
1
+ """``Confirmer.resolve``: confirmation as a resolver parameter (MCP Python SDK 2.x).
2
+
3
+ SDK 2.x fills a tool parameter annotated ``Annotated[T, Resolve(fn)]`` by running
4
+ ``fn`` before the tool body. When ``fn`` returns ``Elicit(...)``, the SDK asks the
5
+ client: on 2026-07-28 connections inside the ``tools/call`` result itself
6
+ (``InputRequiredResult``, then the client retries with the answer), on older ones
7
+ with a normal ``elicitation/create`` request. That is the only way a 2026-07-28
8
+ server can show a prompt, because those connections have no back-channel.
9
+
10
+ ``build_resolve`` returns such a marker. It wires two resolvers:
11
+
12
+ - ``ask``: takes the tool arguments it needs by name. On 2026-07-28 connections
13
+ whose client can show forms it returns ``Elicit(message, confirm: bool)``.
14
+ Everywhere else it runs the normal ``Confirmer.__call__`` (prompt over the
15
+ back-channel, or the token fallback) and returns how the user confirmed.
16
+ - ``check``: depends on ``ask``, receives the full outcome and raises ``Declined``
17
+ unless the user accepted with the box checked.
18
+
19
+ The SDK checks the parameter names at registration, so a name in ``args`` that is
20
+ not a tool argument fails when the tool is registered, not when it is called.
21
+
22
+ No ``from __future__ import annotations`` here: the SDK reads these annotations
23
+ as objects.
24
+ """
25
+
26
+ import inspect
27
+ import string
28
+ from typing import Annotated, Any, Callable, Dict, List, Optional, Sequence
29
+
30
+ from .confirm import client_supports_elicitation, confirmation_schema, interpret
31
+
32
+ _CTX = "askfirst_ctx_"
33
+ _ANSWER = "askfirst_answer_"
34
+
35
+
36
+ def _sdk() -> Any:
37
+ try:
38
+ from mcp.server import mcpserver
39
+ except ImportError as exc: # SDK 1.x or no SDK
40
+ raise ImportError(
41
+ "Confirmer.resolve needs the MCP Python SDK 2.x (mcp>=2, MCPServer). "
42
+ "On SDK 1.x, call `await ask(ctx, ...)` in the tool body instead."
43
+ ) from exc
44
+ return mcpserver
45
+
46
+
47
+ def _template_fields(template: str) -> List[str]:
48
+ names: List[str] = []
49
+ for _, field, _, _ in string.Formatter().parse(template):
50
+ if field is None:
51
+ continue
52
+ name = field.split(".", 1)[0].split("[", 1)[0]
53
+ if not name.isidentifier():
54
+ raise ValueError(f"message template field {field!r} must name a tool argument")
55
+ if name not in names:
56
+ names.append(name)
57
+ return names
58
+
59
+
60
+ def _uses_input_required(ctx: Any) -> bool:
61
+ version = getattr(ctx, "protocol_version", None)
62
+ # Protocol versions are dates, so string order is date order.
63
+ return isinstance(version, str) and version >= "2026-07-28"
64
+
65
+
66
+ def build_resolve(
67
+ confirmer: Any,
68
+ message: Any,
69
+ *,
70
+ action: str,
71
+ args: Optional[Sequence[str]],
72
+ subject: Optional[Callable[[Any], str]],
73
+ ) -> Any:
74
+ sdk = _sdk()
75
+ if not action:
76
+ raise ValueError("action is required")
77
+ if callable(message):
78
+ if args is None:
79
+ raise ValueError("pass args=[...] when message is a function")
80
+ render: Callable[[Dict[str, Any]], str] = lambda values: str(message(**values))
81
+ elif isinstance(message, str):
82
+ render = lambda values: message.format(**values)
83
+ else:
84
+ raise TypeError("message must be a str template or a function")
85
+ names = list(args) if args is not None else _template_fields(message)
86
+ token_param = confirmer.token_param
87
+ for name in names + [token_param]:
88
+ if not name.isidentifier() or name in (_CTX, _ANSWER):
89
+ raise ValueError(f"{name!r} is not a usable tool argument name")
90
+ if token_param in names:
91
+ raise ValueError(f"{token_param!r} is the token parameter; leave it out of args")
92
+
93
+ def split(kw: Dict[str, Any]) -> Dict[str, Any]:
94
+ return {n: kw[n] for n in names}
95
+
96
+ async def ask(**kw: Any) -> Any:
97
+ ctx = kw[_CTX]
98
+ values = split(kw)
99
+ text = render(values)
100
+ if (
101
+ confirmer.mode != "token"
102
+ and _uses_input_required(ctx)
103
+ and client_supports_elicitation(ctx)
104
+ ):
105
+ return sdk.Elicit(text, confirmation_schema())
106
+ how = await confirmer(
107
+ ctx,
108
+ text,
109
+ action=action,
110
+ args=values,
111
+ token=kw.get(token_param) or None,
112
+ subject=subject(ctx) if subject is not None else "",
113
+ )
114
+ return _Done(how)
115
+
116
+ async def check(**kw: Any) -> str:
117
+ outcome = kw[_ANSWER]
118
+ text = render(split(kw))
119
+ data = getattr(outcome, "data", None)
120
+ if isinstance(data, _Done):
121
+ return data.how
122
+ return interpret(getattr(outcome, "action", None), data, text)
123
+
124
+ by_name = [inspect.Parameter(n, inspect.Parameter.KEYWORD_ONLY) for n in names]
125
+ ctx_param = inspect.Parameter(_CTX, inspect.Parameter.KEYWORD_ONLY, annotation=sdk.Context)
126
+ ask.__signature__ = inspect.Signature( # type: ignore[attr-defined]
127
+ [ctx_param, *by_name, inspect.Parameter(token_param, inspect.Parameter.KEYWORD_ONLY)]
128
+ )
129
+ ask.__annotations__ = {_CTX: sdk.Context}
130
+ answer_type = Annotated[sdk.ElicitationResult, sdk.Resolve(ask)]
131
+ check.__signature__ = inspect.Signature( # type: ignore[attr-defined]
132
+ [inspect.Parameter(_ANSWER, inspect.Parameter.KEYWORD_ONLY, annotation=answer_type), *by_name]
133
+ )
134
+ check.__annotations__ = {_ANSWER: answer_type, "return": str}
135
+ # Distinct qualnames keep the SDK's wire keys readable and stable across workers.
136
+ ask.__qualname__ = f"askfirst.{action}.ask"
137
+ check.__qualname__ = f"askfirst.{action}.check"
138
+ return sdk.Resolve(check)
139
+
140
+
141
+ class _Done:
142
+ """A confirmation finished outside the elicitation marker (token or legacy prompt)."""
143
+
144
+ __slots__ = ("how",)
145
+
146
+ def __init__(self, how: str) -> None:
147
+ self.how = how
@@ -173,3 +173,113 @@ def test_read_only_mode_removes_and_blocks_tools():
173
173
  assert names == ["list_branches"]
174
174
  assert is_error(call)
175
175
  assert DELETED == []
176
+
177
+
178
+ # Confirmer.resolve: the prompt as a resolver parameter (SDK 2.x), which also works on
179
+ # 2026-07-28 connections, where the server has no back-channel.
180
+
181
+ v2_only = pytest.mark.skipif(not V2, reason="Resolve(...) parameters need MCP SDK 2.x")
182
+
183
+
184
+ def build_resolved(**confirmer):
185
+ from typing import Annotated
186
+
187
+ ask = Confirmer(**confirmer)
188
+ srv = Server("demo")
189
+
190
+ @srv.tool(annotations=ToolAnnotations(destructiveHint=True))
191
+ async def delete_branch(
192
+ repo: str,
193
+ branch: str,
194
+ how: Annotated[str, ask.resolve("Delete branch {branch} in {repo}?", action="delete_branch")],
195
+ confirm_token: str = "",
196
+ ) -> str:
197
+ DELETED.append(branch)
198
+ return f"deleted {branch} ({how})"
199
+
200
+ return srv
201
+
202
+
203
+ @v2_only
204
+ @pytest.mark.parametrize("modern", [False, True], ids=["2025-11-25", "2026-07-28"])
205
+ def test_resolve_prompt_yes_runs_the_tool(modern):
206
+ cb = answer("accept", True)
207
+
208
+ async def go():
209
+ async with connect(build_resolved(), cb, modern=modern) as c:
210
+ return await c.call_tool("delete_branch", {"repo": "acme/api", "branch": "old"})
211
+
212
+ r = run(go())
213
+ assert not is_error(r), text(r)
214
+ assert text(r) == "deleted old (elicitation)"
215
+ assert cb.messages == ["Delete branch old in acme/api?"]
216
+ assert DELETED == ["old"]
217
+
218
+
219
+ @v2_only
220
+ @pytest.mark.parametrize("modern", [False, True], ids=["2025-11-25", "2026-07-28"])
221
+ @pytest.mark.parametrize("action, confirm", [("decline", None), ("cancel", None), ("accept", False)])
222
+ def test_resolve_prompt_no_stops_the_tool(modern, action, confirm):
223
+ async def go():
224
+ async with connect(build_resolved(), answer(action, confirm), modern=modern) as c:
225
+ return await c.call_tool("delete_branch", {"repo": "acme/api", "branch": "old"})
226
+
227
+ r = run(go())
228
+ assert is_error(r)
229
+ assert "Nothing was done" in text(r) and "Delete branch old in acme/api?" in text(r)
230
+ assert DELETED == []
231
+
232
+
233
+ @v2_only
234
+ @pytest.mark.parametrize("modern", [False, True], ids=["2025-11-25", "2026-07-28"])
235
+ def test_resolve_token_fallback_without_elicitation(modern):
236
+ async def go():
237
+ async with connect(build_resolved(), None, modern=modern) as c:
238
+ args = {"repo": "acme/api", "branch": "old"}
239
+ first = await c.call_tool("delete_branch", args)
240
+ tok = _token(text(first))
241
+ wrong = await c.call_tool("delete_branch", {**args, "branch": "main", "confirm_token": tok})
242
+ ok = await c.call_tool("delete_branch", {**args, "confirm_token": tok})
243
+ return first, wrong, ok
244
+
245
+ first, wrong, ok = run(go())
246
+ assert is_error(first) and "Confirmation required" in text(first)
247
+ assert is_error(wrong) and "different call" in text(wrong)
248
+ assert not is_error(ok) and text(ok) == "deleted old (token)"
249
+ assert DELETED == ["old"]
250
+
251
+
252
+ @v2_only
253
+ def test_resolve_mode_token_skips_the_prompt_on_2026_07_28():
254
+ cb = answer("accept", True)
255
+
256
+ async def go():
257
+ async with connect(build_resolved(mode="token"), cb, modern=True) as c:
258
+ return await c.call_tool("delete_branch", {"repo": "a/b", "branch": "x"})
259
+
260
+ r = run(go())
261
+ assert is_error(r) and "Confirmation required" in text(r)
262
+ assert cb.messages == [] and DELETED == []
263
+
264
+
265
+ @v2_only
266
+ def test_resolve_rejects_unknown_argument_names_at_registration():
267
+ from typing import Annotated
268
+
269
+ ask = Confirmer()
270
+ srv = Server("demo")
271
+ with pytest.raises(Exception, match="nope"):
272
+
273
+ @srv.tool()
274
+ async def drop(
275
+ table: str,
276
+ how: Annotated[str, ask.resolve("Drop {nope}?", action="drop")],
277
+ confirm_token: str = "",
278
+ ) -> str:
279
+ return "dropped"
280
+
281
+
282
+ @pytest.mark.skipif(V2, reason="SDK 1.x behaviour")
283
+ def test_resolve_explains_it_needs_sdk_2():
284
+ with pytest.raises(ImportError, match="SDK 2.x"):
285
+ Confirmer().resolve("Drop {table}?", action="drop")
File without changes
File without changes
File without changes
File without changes