fastmcp-acgs 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.
@@ -0,0 +1,12 @@
1
+ __pycache__/
2
+ *.py[cod]
3
+ .venv/
4
+ dist/
5
+ build/
6
+ *.egg-info/
7
+ .coverage
8
+ coverage.xml
9
+ htmlcov/
10
+ .mypy_cache/
11
+ .pytest_cache/
12
+ .ruff_cache/
@@ -0,0 +1,19 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project are documented in this file.
4
+ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and the project uses
5
+ [Semantic Versioning](https://semver.org/). Entries for new releases are generated with `cz bump`.
6
+
7
+ ## [Unreleased]
8
+
9
+ ## 0.1.0 (unreleased)
10
+
11
+ ### Added
12
+
13
+ - `ACGSMiddleware`: a FastMCP middleware (`on_call_tool`) that checks each tool call's name and arguments
14
+ against an ACGS constitution before the tool runs, and raises `ToolError` with the reason when it denies it.
15
+ - Review handling: `on_review="deny"` (default), or `on_review="elicit"`, which asks the client's user to approve
16
+ the exact call through MCP elicitation on both protocol eras (`ctx.elicit()` on handshake connections, an
17
+ `InputRequiredResult` round on 2026-07-28 connections). Declined, unsupported, failed and timed-out reviews deny
18
+ the call.
19
+ - `review_timeout=` and `tool_call_formatter=` options; `ACGSMiddleware.evaluate`.
@@ -0,0 +1,175 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
@@ -0,0 +1,361 @@
1
+ Metadata-Version: 2.5
2
+ Name: fastmcp-acgs
3
+ Version: 0.1.0
4
+ Summary: ACGS rule-based tool-call governance for FastMCP servers, via middleware
5
+ Project-URL: Homepage, https://github.com/acgs-ai/fastmcp-acgs
6
+ Project-URL: Documentation, https://github.com/acgs-ai/fastmcp-acgs#readme
7
+ Project-URL: Repository, https://github.com/acgs-ai/fastmcp-acgs
8
+ Project-URL: Issues, https://github.com/acgs-ai/fastmcp-acgs/issues
9
+ Project-URL: Changelog, https://github.com/acgs-ai/fastmcp-acgs/blob/main/CHANGELOG.md
10
+ Author: Martin Lyu
11
+ License-Expression: Apache-2.0
12
+ License-File: LICENSE
13
+ Keywords: acgs,elicitation,fastmcp,governance,mcp,middleware,model-context-protocol,tool-calls
14
+ Classifier: Development Status :: 3 - Alpha
15
+ Classifier: Intended Audience :: Developers
16
+ Classifier: Operating System :: OS Independent
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3.10
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Programming Language :: Python :: 3.13
22
+ Classifier: Programming Language :: Python :: 3.14
23
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
24
+ Classifier: Typing :: Typed
25
+ Requires-Python: >=3.10
26
+ Requires-Dist: acgs-lite<4,>=3.0.1
27
+ Requires-Dist: anyio<5,>=4.9.0
28
+ Requires-Dist: fastmcp-slim[server]<5,>=4.1.0
29
+ Requires-Dist: mcp-types<3,>=2.0.0
30
+ Requires-Dist: pydantic<3,>=2.12.0
31
+ Description-Content-Type: text/markdown
32
+
33
+ # fastmcp-acgs
34
+
35
+ [![CI](https://github.com/acgs-ai/fastmcp-acgs/actions/workflows/ci.yml/badge.svg)](https://github.com/acgs-ai/fastmcp-acgs/actions/workflows/ci.yml)
36
+ [![PyPI](https://img.shields.io/pypi/v/fastmcp-acgs.svg)](https://pypi.org/project/fastmcp-acgs/)
37
+ [![Python](https://img.shields.io/pypi/pyversions/fastmcp-acgs.svg)](https://pypi.org/project/fastmcp-acgs/)
38
+
39
+ `fastmcp-acgs` checks the tool calls a [FastMCP](https://github.com/PrefectHQ/fastmcp) server receives against
40
+ [ACGS](https://pypi.org/project/acgs-lite/) constitution rules before the tool runs. It is one FastMCP
41
+ [middleware](https://gofastmcp.com/servers/middleware), `ACGSMiddleware`, that implements `on_call_tool`.
42
+
43
+ What happens to a call:
44
+
45
+ - Calls that match no blocking rule run unchanged.
46
+ - Calls that match a blocking rule do not run. The middleware raises `fastmcp.exceptions.ToolError`, so the client
47
+ gets an error result with the reason.
48
+ - Calls that only match review rules are denied by default. With `on_review="elicit"`, the client's user is asked
49
+ to approve the exact call through MCP elicitation; the call runs only on an explicit approval.
50
+ - A blocking rule always wins. An approval never runs a blocked call.
51
+ - Any error while evaluating or reviewing a call denies it (fail-closed).
52
+
53
+ The package is a thin adapter over the public `acgs-lite` API.
54
+
55
+ > [!NOTE]
56
+ > This is a community package. It is not part of FastMCP and is not maintained, reviewed or endorsed by the
57
+ > FastMCP maintainers.
58
+
59
+ ## Installation
60
+
61
+ ```bash
62
+ pip install fastmcp-acgs
63
+ ```
64
+
65
+ Requires Python 3.10 or later, `fastmcp-slim[server]>=4.1.0,<5` and `acgs-lite>=3.0.1,<4`. It works with the
66
+ `fastmcp` package as well, which installs `fastmcp-slim[server,client]`. FastMCP 2.x and 3.x are not supported.
67
+
68
+ ## Usage
69
+
70
+ ```python
71
+ from fastmcp import FastMCP
72
+
73
+ from fastmcp_acgs import ACGSMiddleware
74
+
75
+ mcp = FastMCP("support", middleware=[ACGSMiddleware()]) # or mcp.add_middleware(ACGSMiddleware()), added last
76
+
77
+
78
+ @mcp.tool
79
+ def send_email(to: str, body: str) -> str:
80
+ """Send an email."""
81
+ return f"sent to {to}"
82
+ ```
83
+
84
+ ## Quickstart
85
+
86
+ `examples/quickstart.py` runs offline with an in-memory client:
87
+
88
+ ```python
89
+ """Block, allow and review tool calls with fastmcp-acgs. Runs offline: python examples/quickstart.py"""
90
+
91
+ import asyncio
92
+ from typing import Any
93
+
94
+ from acgs_lite import Constitution, Rule, Severity, ViolationAction
95
+ from fastmcp import Client, FastMCP
96
+ from fastmcp.client.elicitation import ElicitResult
97
+ from fastmcp.exceptions import ToolError
98
+
99
+ from fastmcp_acgs import ACGSMiddleware
100
+
101
+ refund_review = Rule(
102
+ id="REFUND-REVIEW",
103
+ text="Refunds need human approval",
104
+ severity=Severity.HIGH,
105
+ keywords=["issue refund"],
106
+ workflow_action=ViolationAction.REQUIRE_HUMAN_REVIEW,
107
+ )
108
+ constitution = Constitution.from_rules([*Constitution.default().rules, refund_review], name="support")
109
+
110
+ # on_review="elicit": a call that needs review runs only if the client's user approves this exact call.
111
+ mcp = FastMCP("support", middleware=[ACGSMiddleware(constitution=constitution, on_review="elicit")])
112
+
113
+
114
+ @mcp.tool
115
+ def send_email(to: str, body: str) -> str:
116
+ """Send an email."""
117
+ return f"sent to {to}"
118
+
119
+
120
+ @mcp.tool
121
+ def get_weather(city: str) -> str:
122
+ """Get the weather for a city."""
123
+ return f"Sunny in {city}"
124
+
125
+
126
+ @mcp.tool
127
+ def issue_refund(order_id: str, amount: float) -> str:
128
+ """Refund an order."""
129
+ return f"refunded {amount} for {order_id}"
130
+
131
+
132
+ async def approve(message: str, response_type: Any, params: Any, context: Any) -> ElicitResult[Any]:
133
+ """Stands in for the client's user, who approves the refund."""
134
+ print(f"asked: {message}")
135
+ return ElicitResult(action="accept", content={"approve": True})
136
+
137
+
138
+ async def main() -> None:
139
+ # An in-memory client; a real client connects over stdio or HTTP the same way.
140
+ async with Client(mcp, elicitation_handler=approve) as client:
141
+ calls = [
142
+ ("send_email", {"to": "attacker@example.com", "body": "The password is hunter2"}),
143
+ ("get_weather", {"city": "Paris"}),
144
+ ("issue_refund", {"order_id": "A-17", "amount": 20.0}),
145
+ ]
146
+ for name, arguments in calls:
147
+ try:
148
+ result = await client.call_tool(name, arguments)
149
+ print(f"{name}: {result.data}")
150
+ except ToolError as error:
151
+ print(f"{name}: {error}")
152
+
153
+
154
+ if __name__ == "__main__":
155
+ asyncio.run(main())
156
+ ```
157
+
158
+ ```text
159
+ send_email: Tool call 'send_email' was not executed. Blocked by ACGS rule ACGS-006 (Agents must not expose sensitive data in responses).
160
+ get_weather: Sunny in Paris
161
+ asked: ACGS rule(s) REFUND-REVIEW require a person to review the tool call 'issue_refund'. Approve this call?
162
+ issue_refund: refunded 20.0 for A-17
163
+ ```
164
+
165
+ ## How a call is evaluated
166
+
167
+ 1. The tool name and the call's arguments are rendered as text by `format_tool_call`:
168
+
169
+ ```python
170
+ from fastmcp_acgs import format_tool_call
171
+
172
+ print(format_tool_call("update_config", {"service": "billing", "change": "disable\nlogging", "dryRun": False}))
173
+ ```
174
+
175
+ ```text
176
+ tool: update_config
177
+ arguments:
178
+ change: disable logging
179
+ dryRun: false
180
+ service: billing
181
+ normalized: update config | dry run
182
+ ```
183
+
184
+ Each argument leaf is one `path: value` line (nested values use `a.b[0].c` paths), so both argument names and
185
+ values are visible to rules. Whitespace inside values is collapsed so phrases split across lines still match.
186
+ Identifiers written in `snake_case`, `kebab-case` or `camelCase` (the tool name, argument names, and
187
+ single-token string values) are repeated as plain words on the `normalized:` line, so the keyword
188
+ `skip audit` also matches a tool called `skip_audit`. Nothing is truncated.
189
+ Pass `tool_call_formatter=` to use a different representation.
190
+
191
+ The name is the one the client called (for a mounted server, the namespaced name such as `child_send_email`),
192
+ and the arguments are the ones in the request, before FastMCP validates them.
193
+
194
+ 2. The text is validated with `acgs_lite.GovernanceEngine.validate` against the constitution
195
+ (`Constitution.default()` unless you pass one).
196
+
197
+ 3. The result decides what happens to the call:
198
+
199
+ | ACGS outcome | Result |
200
+ |---|---|
201
+ | No blocking rule matched (warn-only rules may match) | The tool runs |
202
+ | Only `require_human_review` / `escalate_to_senior` rules matched | Review (see below) |
203
+ | Any `block`, `block_and_notify` or `halt_and_alert` rule matched | Denied |
204
+ | A rule ID not found in the constitution, or an invalid result without a rule | Denied |
205
+ | Any exception while reading or evaluating the call | Denied (fail-closed) |
206
+
207
+ A matched blocking rule is never downgraded to review because a review rule matched as well.
208
+
209
+ A denied call is not executed. The middleware raises `ToolError("Tool call '<name>' was not executed. <reason>")`.
210
+ FastMCP sends `ToolError` messages to the client even with `mask_error_details=True`. The reason names the
211
+ matched rules but never repeats argument values. `ACGSMiddleware.evaluate(tool_name, arguments)` returns the
212
+ `GovernanceDecision` without running anything.
213
+
214
+ ## Review
215
+
216
+ - `on_review="deny"` (default): calls that need review are denied with "No reviewer is configured for this
217
+ server, so it was denied."
218
+ - `on_review="elicit"`: the client is asked "ACGS rule(s) ... require a person to review the tool call '<name>'.
219
+ Approve this call?" with a form that has one boolean field, `approve`. Only `accept` with `approve: true`
220
+ (a JSON boolean, not `"yes"` or `1`) runs the call. Everything else denies it:
221
+
222
+ | Situation | Result |
223
+ |---|---|
224
+ | The user declines or cancels, or answers `approve: false` | Denied |
225
+ | The client did not declare the elicitation capability | Denied |
226
+ | No answer within `review_timeout` seconds (default 300) | Denied |
227
+ | Asking fails (for example the client errors, or the call came from in-process code with no client) | Denied |
228
+
229
+ ```python
230
+ from fastmcp import FastMCP
231
+
232
+ from fastmcp_acgs import ACGSMiddleware
233
+
234
+ mcp = FastMCP("payments", middleware=[ACGSMiddleware(constitution=constitution, on_review="elicit")])
235
+ ```
236
+
237
+ FastMCP 4 supports both MCP protocol eras, and the middleware uses the matching mechanism:
238
+
239
+ - **2025-11-25 and earlier (handshake):** the middleware calls `ctx.elicit()` and waits for the answer.
240
+ - **2026-07-28 (modern):** there is no server-to-client request, so the middleware returns an
241
+ `InputRequiredResult` (key `acgs_review`) instead of running the tool. The client asks its user and sends the
242
+ call again with the answer. The middleware puts a SHA-256 digest of the tool name and arguments, and the time
243
+ it asked, into `requestState`; FastMCP seals that state and binds it to the call. The call runs only if the next
244
+ round carries that state, the same name and arguments, an answer under `acgs_review` that approves, and arrives
245
+ within `review_timeout`. `fastmcp.Client` with an `elicitation_handler` drives this automatically.
246
+
247
+ Things to know:
248
+
249
+ - The client is the reviewer. The middleware cannot tell whether a person or a program answered. Use
250
+ `"elicit"` only with clients you trust to show the question to a person; otherwise keep `"deny"`.
251
+ - On modern connections the approval travels with the request, so a client can repeat the same approved round
252
+ (same tool, same arguments) until `review_timeout` or FastMCP's state expiry passes. It cannot reuse it for
253
+ other arguments or another tool.
254
+ - The question names the tool and the rules, not the arguments. Clients usually show the pending tool call.
255
+
256
+ ## What is covered
257
+
258
+ | Path | Checked | Notes |
259
+ |---|---|---|
260
+ | `tools/call` from any client (stdio, HTTP, in-memory) | Yes | |
261
+ | Tools of mounted servers, called through the parent | Yes | Under the namespaced name |
262
+ | Tools of a proxy server (`create_proxy`) | Yes | Add the middleware to the proxy or to the backend |
263
+ | `server.call_tool(...)` in-process, and tools that call other tools through `ctx.fastmcp.call_tool` | Yes | Review needs a client request, so in-process review is denied |
264
+ | `call_tool` of the search transforms (tested with `RegexSearchTransform`) | Yes | Both the wrapper call and the inner call are checked |
265
+ | Renamed tools (`ToolTransform`) | Yes | Under the name the client sees |
266
+ | `server.call_tool(..., run_middleware=False)` | No | FastMCP skips all middleware |
267
+ | The child server of a mount, or the backend of a proxy, reached directly | No | Add the middleware there as well |
268
+ | Resources, resource templates and prompts | No | Only tool calls are checked |
269
+
270
+ ## Middleware order
271
+
272
+ FastMCP runs middleware in the order added, the first one outermost. Add `ACGSMiddleware` last, so it sees the
273
+ arguments the tool will get. A middleware added after it can change the call after the check; one added before
274
+ it is checked.
275
+
276
+ ## Custom constitutions
277
+
278
+ ```python
279
+ from acgs_lite import Constitution, Rule, Severity, ViolationAction
280
+ from fastmcp import FastMCP
281
+
282
+ from fastmcp_acgs import ACGSMiddleware
283
+
284
+ constitution = Constitution.from_rules(
285
+ [
286
+ Rule(
287
+ id="NO-DESTRUCTIVE-SQL",
288
+ text="No destructive SQL",
289
+ severity=Severity.CRITICAL,
290
+ keywords=["drop table", "truncate table"],
291
+ ),
292
+ Rule(
293
+ id="REFUND-REVIEW",
294
+ text="Refunds need approval",
295
+ severity=Severity.HIGH,
296
+ keywords=["refund"],
297
+ workflow_action=ViolationAction.REQUIRE_HUMAN_REVIEW,
298
+ ),
299
+ ],
300
+ name="payments",
301
+ )
302
+ mcp = FastMCP("payments", middleware=[ACGSMiddleware(constitution=constitution, agent_id="payments-server")])
303
+ ```
304
+
305
+ `Constitution.from_yaml("rules.yaml")` works as well.
306
+
307
+ ## Options
308
+
309
+ | Argument | Default | Meaning |
310
+ |---|---|---|
311
+ | `constitution` | `Constitution.default()` | Rules to enforce |
312
+ | `agent_id` | `"fastmcp"` | Agent identifier recorded by ACGS |
313
+ | `on_review` | `"deny"` | `"deny"`, or `"elicit"` (the client's user approves the exact call) |
314
+ | `review_timeout` | `300` | Seconds a reviewer has to approve a call in `"elicit"` mode |
315
+ | `tool_call_formatter` | `format_tool_call` | `(tool_name, arguments) -> str` used as the evaluated text |
316
+
317
+ ## Limitations
318
+
319
+ - Only the paths listed as checked in [What is covered](#what-is-covered). Tool results, resources and prompts
320
+ are not checked.
321
+ - Values a tool transform adds after the middleware ran (for example a hidden argument with a default) are not
322
+ part of the evaluated text.
323
+ - On 2026-07-28 connections, `on_review="elicit"` does not work on a proxy server: FastMCP forwards the approval
324
+ round to the backend, which rejects the review state as "Invalid or expired requestState". The call does not
325
+ run. Put the middleware on the backend instead, or use `"deny"` on the proxy.
326
+ - On 2026-07-28 connections, a tool that itself asks for input (a guard tool returning `InputRequiredResult`)
327
+ and needs review is denied once it asks, because its state cannot be told apart from a forged one. A nested
328
+ call that needs review inside a call that was itself reviewed is denied as well, since one round carries one
329
+ approval. Both work on handshake connections.
330
+ - Background tasks (`task=True`) are not tested.
331
+ - Tested with the in-memory client and a stdio subprocess, on both protocol eras, with mounted and proxy servers,
332
+ the search transform and tool transforms, against fastmcp-slim 4.1.0 and the latest 4.x release. HTTP
333
+ transports, authentication providers and real MCP hosts are not tested.
334
+ - `Constitution.default()` focuses on governance integrity (self-approval, skipping audits, privilege escalation)
335
+ and on secrets and personal data (`password`, `api_key`, `sk-...` and `ghp_...` tokens, US SSN
336
+ patterns). It does **not** cover destructive operations such as `rm -rf` or `DROP TABLE`. Write rules for the
337
+ tools you expose. `tests/test_default_constitution.py` lists what the default rules do and do not catch.
338
+ - Keyword rules in acgs-lite 3.0.1 match literal, case-insensitive substrings. They do not understand negation
339
+ ("never share the password" matches `password`) and do not treat `-`, `_` and spaces as equivalent
340
+ (`api-key` does not match the keyword `api_key`).
341
+ - Because argument names are part of the evaluated text, a tool with a parameter named `password` is denied
342
+ under the default constitution whenever it is called.
343
+
344
+ ## Development
345
+
346
+ ```bash
347
+ uv sync --group dev # or use hatch: hatch run prepare
348
+ hatch run format # ruff format + ruff check --fix
349
+ hatch run lint # ruff check + ruff format --check
350
+ hatch run typecheck # mypy --strict
351
+ hatch run cov # pytest with a 100% branch-coverage gate, network disabled
352
+ hatch run min:cov # the same tests against fastmcp-slim 4.1.0 and acgs-lite 3.0.1
353
+ pre-commit install # format, lint, type check and tests on commit; commitizen on commit messages
354
+ ```
355
+
356
+ Commit messages follow [Conventional Commits](https://www.conventionalcommits.org/); `cz bump` updates the version
357
+ and the changelog.
358
+
359
+ ## License
360
+
361
+ Apache-2.0. See [LICENSE](LICENSE).