askfirst 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
askfirst/__init__.py ADDED
@@ -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
+ ]
askfirst/confirm.py ADDED
@@ -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)
askfirst/errors.py ADDED
@@ -0,0 +1,62 @@
1
+ """Exceptions raised by askfirst.
2
+
3
+ They subclass the MCP SDK's own ``ToolError`` classes (whichever of them are
4
+ installed), so the server sends their message to the model as the tool's error
5
+ result instead of hiding it as a crash.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import importlib
11
+ from typing import Optional, Tuple, Type
12
+
13
+
14
+ def _tool_error_bases() -> Tuple[Type[Exception], ...]:
15
+ bases = []
16
+ for module in (
17
+ "mcp.server.mcpserver.exceptions", # MCP Python SDK 2.x (MCPServer)
18
+ "mcp.server.fastmcp.exceptions", # MCP Python SDK 1.x (FastMCP)
19
+ "fastmcp.exceptions", # the standalone fastmcp package
20
+ ):
21
+ try:
22
+ cls = getattr(importlib.import_module(module), "ToolError")
23
+ except Exception: # not installed, or a version without it
24
+ continue
25
+ if isinstance(cls, type) and issubclass(cls, Exception) and cls not in bases:
26
+ bases.append(cls)
27
+ # Drop any base that is a subclass of another, so the MRO stays valid.
28
+ bases = [b for b in bases if not any(o is not b and issubclass(o, b) for o in bases)]
29
+ return tuple(bases) or (Exception,)
30
+
31
+
32
+ class AskFirstError(*_tool_error_bases()): # type: ignore[misc]
33
+ """Base class. The message is written for the model that called the tool."""
34
+
35
+
36
+ class ConfirmationRequired(AskFirstError):
37
+ """The user has not confirmed yet. The message tells the model how to continue.
38
+
39
+ Raised when the client cannot show a confirmation prompt (no elicitation
40
+ support). ``token`` is the confirmation token the model must send back on its
41
+ next call, after the user agrees.
42
+ """
43
+
44
+ def __init__(self, text: str, *, token: str, expires_in: int, reason: Optional[str] = None):
45
+ super().__init__(text)
46
+ self.token = token
47
+ self.expires_in = expires_in
48
+ #: Why an earlier token was refused, if one was sent ("expired", "used", ...).
49
+ self.reason = reason
50
+
51
+
52
+ class Declined(AskFirstError):
53
+ """The user said no, closed the prompt, or did not answer in time."""
54
+
55
+ def __init__(self, text: str, *, action: str = "decline"):
56
+ super().__init__(text)
57
+ #: "decline", "cancel" or "timeout".
58
+ self.action = action
59
+
60
+
61
+ class ConfirmationUnavailable(AskFirstError):
62
+ """``mode="elicit"`` was set and the client cannot show a confirmation prompt."""
askfirst/restrict.py ADDED
@@ -0,0 +1,146 @@
1
+ """Read-only mode and tool allow/deny lists for an MCP server.
2
+
3
+ ``restrict`` removes tools from the server itself, so a hidden tool is not just
4
+ missing from ``tools/list``: calling it by name fails too. Read-only mode keeps
5
+ only tools that declare ``readOnlyHint=True``. A tool with no annotations is
6
+ treated as one that writes (fail closed).
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import fnmatch
12
+ import os
13
+ from typing import Any, Iterable, List, Mapping, Optional, Sequence
14
+
15
+ __all__ = ["restrict", "restrict_from_env", "is_read_only"]
16
+
17
+ _TRUE = {"1", "true", "yes", "on"}
18
+ _FALSE = {"", "0", "false", "no", "off"}
19
+
20
+
21
+ def is_read_only(tool: Any) -> bool:
22
+ """True only if the tool's annotations say ``readOnlyHint`` is true."""
23
+ annotations = getattr(tool, "annotations", None)
24
+ if annotations is None:
25
+ return False
26
+ if isinstance(annotations, Mapping):
27
+ value = annotations.get("readOnlyHint", annotations.get("read_only_hint"))
28
+ else:
29
+ value = getattr(annotations, "readOnlyHint", None)
30
+ if value is None:
31
+ value = getattr(annotations, "read_only_hint", None)
32
+ return value is True
33
+
34
+
35
+ def _tool_manager(server: Any) -> Any:
36
+ manager = getattr(server, "_tool_manager", None)
37
+ if manager is None or not hasattr(manager, "list_tools"):
38
+ raise TypeError(
39
+ "restrict() needs an MCP Python SDK server (FastMCP from mcp 1.x or MCPServer from "
40
+ f"mcp 2.x); got {type(server).__module__}.{type(server).__name__}"
41
+ )
42
+ return manager
43
+
44
+
45
+ def _matches(name: str, patterns: Sequence[str]) -> bool:
46
+ return any(fnmatch.fnmatchcase(name, p) for p in patterns)
47
+
48
+
49
+ def _clean(patterns: Optional[Iterable[str]]) -> Optional[List[str]]:
50
+ if patterns is None:
51
+ return None
52
+ if isinstance(patterns, str):
53
+ patterns = patterns.split(",")
54
+ return [p.strip() for p in patterns if p and p.strip()]
55
+
56
+
57
+ def restrict(
58
+ server: Any,
59
+ *,
60
+ read_only: bool = False,
61
+ allow: Optional[Iterable[str]] = None,
62
+ deny: Optional[Iterable[str]] = None,
63
+ ) -> List[str]:
64
+ """Remove the tools this deployment must not offer. Call it after registering tools.
65
+
66
+ Args:
67
+ server: A ``FastMCP`` (mcp 1.x) or ``MCPServer`` (mcp 2.x) instance.
68
+ read_only: Keep only tools annotated ``readOnlyHint=True``.
69
+ allow: If given, keep only tools whose name matches one of these glob
70
+ patterns (``"list_*"``, ``"get_issue"``). An empty list removes all.
71
+ deny: Remove tools matching any of these patterns. Deny wins over allow.
72
+
73
+ Returns:
74
+ The names of the removed tools, sorted.
75
+
76
+ Raises:
77
+ ValueError: If an ``allow`` or ``deny`` pattern matches no tool, which is
78
+ almost always a typo that would silently leave a tool exposed or
79
+ hidden.
80
+ """
81
+ manager = _tool_manager(server)
82
+ allow_p = _clean(allow)
83
+ deny_p = _clean(deny) or []
84
+ tools = list(manager.list_tools())
85
+ names = [t.name for t in tools]
86
+ for label, patterns in (("allow", allow_p or []), ("deny", deny_p)):
87
+ unknown = [p for p in patterns if not any(fnmatch.fnmatchcase(n, p) for n in names)]
88
+ if unknown:
89
+ raise ValueError(f"{label} pattern(s) match no tool: {', '.join(unknown)}")
90
+
91
+ removed = []
92
+ for tool in tools:
93
+ name = tool.name
94
+ keep = True
95
+ if allow_p is not None and not _matches(name, allow_p):
96
+ keep = False
97
+ if _matches(name, deny_p):
98
+ keep = False
99
+ if read_only and not is_read_only(tool):
100
+ keep = False
101
+ if not keep:
102
+ removed.append(name)
103
+ remove = _remover(server, manager)
104
+ for name in removed:
105
+ remove(name)
106
+ return sorted(removed)
107
+
108
+
109
+ def _remover(server: Any, manager: Any) -> Any:
110
+ if callable(getattr(server, "remove_tool", None)):
111
+ return server.remove_tool
112
+ if callable(getattr(manager, "remove_tool", None)):
113
+ return manager.remove_tool
114
+ tools = getattr(manager, "_tools", None) # mcp < 1.11 has no remove_tool
115
+ if isinstance(tools, dict):
116
+ return tools.__delitem__
117
+ raise TypeError(f"cannot remove tools from {type(server).__name__}")
118
+
119
+
120
+ def _flag(env: Mapping[str, str], key: str) -> bool:
121
+ raw = env.get(key, "").strip().lower()
122
+ if raw in _TRUE:
123
+ return True
124
+ if raw in _FALSE:
125
+ return False
126
+ raise ValueError(f"{key} must be true or false, not {env[key]!r}")
127
+
128
+
129
+ def restrict_from_env(
130
+ server: Any, prefix: str = "MCP", env: Optional[Mapping[str, str]] = None
131
+ ) -> List[str]:
132
+ """``restrict`` configured by environment variables, for users of your server.
133
+
134
+ ``<PREFIX>_READ_ONLY=true``, ``<PREFIX>_ALLOW_TOOLS=list_*,get_*`` and
135
+ ``<PREFIX>_DENY_TOOLS=delete_*`` (comma-separated glob patterns). Unset
136
+ variables change nothing.
137
+ """
138
+ env = os.environ if env is None else env
139
+ allow = env.get(f"{prefix}_ALLOW_TOOLS")
140
+ deny = env.get(f"{prefix}_DENY_TOOLS")
141
+ return restrict(
142
+ server,
143
+ read_only=_flag(env, f"{prefix}_READ_ONLY"),
144
+ allow=_clean(allow) if allow is not None else None,
145
+ deny=_clean(deny) if deny is not None else None,
146
+ )
askfirst/tokens.py ADDED
@@ -0,0 +1,138 @@
1
+ """Confirmation tokens: signed, short-lived, single-use, bound to one exact call.
2
+
3
+ A token is ``<expiry>.<nonce>.<signature>``. The signature is an HMAC-SHA256 over
4
+ the action name, a digest of the call's arguments, an optional subject (the user
5
+ or session), the expiry and the nonce. Nothing secret is inside the token, and the
6
+ action and arguments are not stored in it: they are taken from the call that
7
+ presents it, so a token issued for ``delete("staging")`` does not work for
8
+ ``delete("prod")``.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import base64
14
+ import hashlib
15
+ import hmac
16
+ import json
17
+ import secrets
18
+ import threading
19
+ import time
20
+ from typing import Any, Callable, Dict, Mapping, Optional
21
+
22
+ __all__ = ["TokenSigner", "MemoryNonceStore", "canonical_args"]
23
+
24
+ _VERSION = b"askfirst.v1"
25
+
26
+
27
+ def canonical_args(args: Optional[Mapping[str, Any]]) -> bytes:
28
+ """A stable byte form of the call's arguments (key order does not matter)."""
29
+ return json.dumps(
30
+ dict(args or {}), sort_keys=True, separators=(",", ":"), ensure_ascii=False, default=repr
31
+ ).encode("utf-8")
32
+
33
+
34
+ def _b64(data: bytes) -> str:
35
+ return base64.urlsafe_b64encode(data).rstrip(b"=").decode("ascii")
36
+
37
+
38
+ class MemoryNonceStore:
39
+ """Remembers used tokens until they expire, in this process only.
40
+
41
+ With several server processes behind a load balancer, pass a store shared
42
+ between them (anything with this ``use`` method), or a token could be used
43
+ once per process.
44
+ """
45
+
46
+ def __init__(self, clock: Callable[[], float] = time.time):
47
+ self._used: Dict[str, float] = {}
48
+ self._lock = threading.Lock()
49
+ self._clock = clock
50
+
51
+ def use(self, nonce: str, expires_at: float) -> bool:
52
+ """Mark ``nonce`` used. False if it was already used."""
53
+ with self._lock:
54
+ now = self._clock()
55
+ if len(self._used) > 1024:
56
+ self._used = {n: e for n, e in self._used.items() if e > now}
57
+ if nonce in self._used:
58
+ return False
59
+ self._used[nonce] = expires_at
60
+ return True
61
+
62
+
63
+ class TokenSigner:
64
+ """Issues and checks confirmation tokens.
65
+
66
+ ``secret`` defaults to random bytes made at start-up, so tokens stop working
67
+ when the server restarts. Pass a fixed secret (32+ random bytes) to keep them
68
+ valid across restarts or between processes.
69
+ """
70
+
71
+ def __init__(
72
+ self,
73
+ secret: Optional[bytes] = None,
74
+ *,
75
+ ttl: int = 300,
76
+ store: Optional[Any] = None,
77
+ clock: Callable[[], float] = time.time,
78
+ ):
79
+ if secret is not None and isinstance(secret, str):
80
+ secret = secret.encode("utf-8")
81
+ if secret is not None and len(secret) < 16:
82
+ raise ValueError("secret must be at least 16 bytes")
83
+ if ttl <= 0:
84
+ raise ValueError("ttl must be positive")
85
+ self._secret = secret or secrets.token_bytes(32)
86
+ self.ttl = int(ttl)
87
+ self._clock = clock
88
+ self._store = store if store is not None else MemoryNonceStore(clock)
89
+
90
+ def _sign(self, action: str, args: Optional[Mapping[str, Any]], subject: str, exp: int, nonce: str) -> str:
91
+ msg = b"\n".join(
92
+ [
93
+ _VERSION,
94
+ action.encode("utf-8"),
95
+ hashlib.sha256(canonical_args(args)).digest(),
96
+ subject.encode("utf-8"),
97
+ str(exp).encode("ascii"),
98
+ nonce.encode("ascii"),
99
+ ]
100
+ )
101
+ return _b64(hmac.new(self._secret, msg, hashlib.sha256).digest())
102
+
103
+ def issue(self, action: str, args: Optional[Mapping[str, Any]] = None, subject: str = "") -> str:
104
+ """A new token for exactly this action, these arguments and this subject."""
105
+ exp = int(self._clock()) + self.ttl
106
+ nonce = _b64(secrets.token_bytes(12))
107
+ return f"{exp}.{nonce}.{self._sign(action, args, subject, exp, nonce)}"
108
+
109
+ def check(
110
+ self,
111
+ token: str,
112
+ action: str,
113
+ args: Optional[Mapping[str, Any]] = None,
114
+ subject: str = "",
115
+ ) -> Optional[str]:
116
+ """Check and use up ``token``. Returns None if it is valid, else the reason.
117
+
118
+ Reasons: ``"malformed"``, ``"mismatch"`` (signed for another action, other
119
+ arguments, another subject, or by another secret), ``"expired"``, ``"used"``.
120
+ """
121
+ if not isinstance(token, str) or len(token) > 200:
122
+ return "malformed"
123
+ parts = token.strip().split(".")
124
+ if len(parts) != 3 or not parts[0].isdigit() or not parts[1] or not parts[2]:
125
+ return "malformed"
126
+ exp_s, nonce, sig = parts
127
+ exp = int(exp_s)
128
+ try:
129
+ nonce.encode("ascii")
130
+ except UnicodeEncodeError:
131
+ return "malformed"
132
+ if not hmac.compare_digest(self._sign(action, args, subject, exp, nonce), sig):
133
+ return "mismatch"
134
+ if self._clock() >= exp:
135
+ return "expired"
136
+ if not self._store.use(nonce, float(exp)):
137
+ return "used"
138
+ return None
@@ -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
@@ -0,0 +1,9 @@
1
+ askfirst/__init__.py,sha256=rgZg8FAoMk3IWaHi8Q7jJ6b-ROHX8TC0NLzC1gWIBi8,1066
2
+ askfirst/confirm.py,sha256=1Jm4y0kHZofEOUhXZylgSNX2F-U1obbaGyfMEgqMglw,9188
3
+ askfirst/errors.py,sha256=0xa_reULr1w9gw64RZX4CN_mIGYgrWAmSge-AT40_ms,2341
4
+ askfirst/restrict.py,sha256=egVXBMrXv6fomZ1tpUpHCZIploZa7fdvhMR754Ewb3o,5174
5
+ askfirst/tokens.py,sha256=oFBtHpgpNOR3KsTjYs_RCgbltab04i3HJzbvg0jm2qk,5038
6
+ askfirst-0.1.0.dist-info/METADATA,sha256=eD6pBKNHYoSq9Ea8tIos8X4YaITV-v79k40WnSRsMkQ,8160
7
+ askfirst-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
8
+ askfirst-0.1.0.dist-info/licenses/LICENSE,sha256=fl9U1idgeyJw-8GWneEYxVzZM_C29cBR63IAlNv7KjE,1080
9
+ askfirst-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,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.