gvn-tools 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.
Files changed (43) hide show
  1. gvn_tools-0.1.0/.gitignore +29 -0
  2. gvn_tools-0.1.0/LICENSE +202 -0
  3. gvn_tools-0.1.0/PKG-INFO +50 -0
  4. gvn_tools-0.1.0/README.md +26 -0
  5. gvn_tools-0.1.0/pyproject.toml +37 -0
  6. gvn_tools-0.1.0/src/gvn_tools/__init__.py +1 -0
  7. gvn_tools-0.1.0/src/gvn_tools/fakes.py +302 -0
  8. gvn_tools-0.1.0/src/gvn_tools/files.py +768 -0
  9. gvn_tools-0.1.0/src/gvn_tools/git.py +825 -0
  10. gvn_tools-0.1.0/src/gvn_tools/github.py +873 -0
  11. gvn_tools-0.1.0/src/gvn_tools/jira_cloud.py +1018 -0
  12. gvn_tools-0.1.0/src/gvn_tools/mcp.py +1144 -0
  13. gvn_tools-0.1.0/src/gvn_tools/process.py +349 -0
  14. gvn_tools-0.1.0/src/gvn_tools/protocol.py +613 -0
  15. gvn_tools-0.1.0/src/gvn_tools/retrying.py +20 -0
  16. gvn_tools-0.1.0/src/gvn_tools/rules.py +273 -0
  17. gvn_tools-0.1.0/src/gvn_tools/shell.py +270 -0
  18. gvn_tools-0.1.0/src/gvn_tools/transport.py +347 -0
  19. gvn_tools-0.1.0/src/gvn_tools/web.py +564 -0
  20. gvn_tools-0.1.0/src/gvn_tools/workspace.py +155 -0
  21. gvn_tools-0.1.0/tests/conftest.py +60 -0
  22. gvn_tools-0.1.0/tests/live/test_live_coding_agent.py +760 -0
  23. gvn_tools-0.1.0/tests/live/test_live_github.py +484 -0
  24. gvn_tools-0.1.0/tests/live/test_live_jira_cloud.py +498 -0
  25. gvn_tools-0.1.0/tests/live/test_live_mcp.py +100 -0
  26. gvn_tools-0.1.0/tests/live/test_live_web.py +418 -0
  27. gvn_tools-0.1.0/tests/mcp_notes_server.py +83 -0
  28. gvn_tools-0.1.0/tests/test_rules_exposed.py +138 -0
  29. gvn_tools-0.1.0/tests/test_tools_files.py +721 -0
  30. gvn_tools-0.1.0/tests/test_tools_git.py +1014 -0
  31. gvn_tools-0.1.0/tests/test_tools_github.py +679 -0
  32. gvn_tools-0.1.0/tests/test_tools_identity.py +193 -0
  33. gvn_tools-0.1.0/tests/test_tools_jira_cloud.py +904 -0
  34. gvn_tools-0.1.0/tests/test_tools_mcp.py +1059 -0
  35. gvn_tools-0.1.0/tests/test_tools_mcp_server.py +252 -0
  36. gvn_tools-0.1.0/tests/test_tools_process.py +265 -0
  37. gvn_tools-0.1.0/tests/test_tools_retries.py +264 -0
  38. gvn_tools-0.1.0/tests/test_tools_rules.py +241 -0
  39. gvn_tools-0.1.0/tests/test_tools_shell.py +423 -0
  40. gvn_tools-0.1.0/tests/test_tools_transport.py +349 -0
  41. gvn_tools-0.1.0/tests/test_tools_web.py +587 -0
  42. gvn_tools-0.1.0/tests/test_tools_workspace.py +270 -0
  43. gvn_tools-0.1.0/tests/test_untrusted_tools.py +68 -0
@@ -0,0 +1,29 @@
1
+ .env
2
+ .venv/
3
+ __pycache__/
4
+ *.pyc
5
+ .pytest_cache/
6
+ .ruff_cache/
7
+ .import_linter_cache/
8
+ .hypothesis/
9
+ dist/
10
+ .ticket_to_pr/
11
+ .gvn/
12
+
13
+ # macOS
14
+ .DS_Store
15
+
16
+ # Caches
17
+ .grimp_cache/
18
+ .claude/
19
+
20
+ # Node and site builds
21
+ node_modules/
22
+ /site/
23
+ website/.astro/
24
+ website/src/generated/
25
+ website/test-results/
26
+ website/playwright-report/
27
+
28
+ # Local video tooling, kept out of the repository for now
29
+ /tools/
@@ -0,0 +1,202 @@
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.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,50 @@
1
+ Metadata-Version: 2.5
2
+ Name: gvn-tools
3
+ Version: 0.1.0
4
+ Summary: Ready-made tools for gvn harnesses: files, shell, git, HTTP, issue trackers, each with its safety rules.
5
+ Project-URL: Homepage, https://gvn-harness.dev
6
+ Project-URL: Documentation, https://gvn-harness.dev/paths/
7
+ Project-URL: Repository, https://github.com/humbertopoliti/gvn
8
+ Project-URL: Changelog, https://github.com/humbertopoliti/gvn/blob/main/CHANGELOG.md
9
+ Author: Humberto Politi
10
+ License-Expression: Apache-2.0
11
+ License-File: LICENSE
12
+ Keywords: agents,llm,mcp,tools
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Topic :: Software Development :: Libraries
17
+ Requires-Python: >=3.12
18
+ Requires-Dist: gvn
19
+ Provides-Extra: http
20
+ Requires-Dist: httpx2>=1.0; extra == 'http'
21
+ Provides-Extra: mcp
22
+ Requires-Dist: mcp>=2.0; extra == 'mcp'
23
+ Description-Content-Type: text/markdown
24
+
25
+ # gvn-tools
26
+
27
+ **Ready-made tools for gvn harnesses, each with its safety rules.**
28
+
29
+ `gvn-tools` gives a [gvn](https://github.com/humbertopoliti/gvn) agent tools for files, a
30
+ shell, git, the web, Jira Cloud, GitHub and any MCP server, and `Rules` for writing the
31
+ policy that decides which calls run, which need a person's approval and which are forbidden.
32
+
33
+ ```bash
34
+ pip install gvn-tools
35
+ pip install "gvn-tools[http,mcp]" # web, Jira Cloud and GitHub tools; MCP servers
36
+ ```
37
+
38
+ The tools confine themselves to a workspace and to allow-lists of programs and hosts. A
39
+ tool whose results may hold text written outside your control says so, and the agent
40
+ records it. The [tools documentation](https://gvn-harness.dev/tools/) describes each family.
41
+
42
+ ## Documentation and source
43
+
44
+ - Documentation: <https://gvn-harness.dev>
45
+ - Source, issues and the other gvn packages: <https://github.com/humbertopoliti/gvn>
46
+ - Changelog: <https://github.com/humbertopoliti/gvn/blob/main/CHANGELOG.md>
47
+
48
+ ## License
49
+
50
+ [Apache License 2.0](https://github.com/humbertopoliti/gvn/blob/main/LICENSE)
@@ -0,0 +1,26 @@
1
+ # gvn-tools
2
+
3
+ **Ready-made tools for gvn harnesses, each with its safety rules.**
4
+
5
+ `gvn-tools` gives a [gvn](https://github.com/humbertopoliti/gvn) agent tools for files, a
6
+ shell, git, the web, Jira Cloud, GitHub and any MCP server, and `Rules` for writing the
7
+ policy that decides which calls run, which need a person's approval and which are forbidden.
8
+
9
+ ```bash
10
+ pip install gvn-tools
11
+ pip install "gvn-tools[http,mcp]" # web, Jira Cloud and GitHub tools; MCP servers
12
+ ```
13
+
14
+ The tools confine themselves to a workspace and to allow-lists of programs and hosts. A
15
+ tool whose results may hold text written outside your control says so, and the agent
16
+ records it. The [tools documentation](https://gvn-harness.dev/tools/) describes each family.
17
+
18
+ ## Documentation and source
19
+
20
+ - Documentation: <https://gvn-harness.dev>
21
+ - Source, issues and the other gvn packages: <https://github.com/humbertopoliti/gvn>
22
+ - Changelog: <https://github.com/humbertopoliti/gvn/blob/main/CHANGELOG.md>
23
+
24
+ ## License
25
+
26
+ [Apache License 2.0](https://github.com/humbertopoliti/gvn/blob/main/LICENSE)
@@ -0,0 +1,37 @@
1
+ [project]
2
+ name = "gvn-tools"
3
+ version = "0.1.0"
4
+ description = "Ready-made tools for gvn harnesses: files, shell, git, HTTP, issue trackers, each with its safety rules."
5
+ requires-python = ">=3.12"
6
+ license = "Apache-2.0"
7
+ license-files = ["LICENSE"]
8
+ readme = "README.md"
9
+ authors = [{ name = "Humberto Politi" }]
10
+ keywords = ["agents", "llm", "tools", "mcp"]
11
+ classifiers = [
12
+ "Intended Audience :: Developers",
13
+ "Programming Language :: Python :: 3",
14
+ "Programming Language :: Python :: 3.12",
15
+ "Topic :: Software Development :: Libraries",
16
+ ]
17
+ dependencies = ["gvn"]
18
+
19
+ [project.optional-dependencies]
20
+ http = ["httpx2>=1.0"]
21
+ mcp = ["mcp>=2.0"]
22
+
23
+ [project.urls]
24
+ Homepage = "https://gvn-harness.dev"
25
+ Documentation = "https://gvn-harness.dev/paths/"
26
+ Repository = "https://github.com/humbertopoliti/gvn"
27
+ Changelog = "https://github.com/humbertopoliti/gvn/blob/main/CHANGELOG.md"
28
+
29
+ [build-system]
30
+ requires = ["hatchling"]
31
+ build-backend = "hatchling.build"
32
+
33
+ [tool.hatch.build.targets.wheel]
34
+ packages = ["src/gvn_tools"]
35
+
36
+ [tool.hatch.build.targets.sdist]
37
+ include = ["/src", "/tests", "/README.md", "/LICENSE"]
@@ -0,0 +1 @@
1
+ """gvn_tools: ready-made tools for gvn harnesses, each with its safety rules."""
@@ -0,0 +1,302 @@
1
+ """gvn_tools.fakes: in-memory ports for tests. See the tools contract.
2
+
3
+ ``FakeCommands`` (scripted results per argv, records calls) stands in for
4
+ ``gvn_tools.process.Commands``; ``FakeHttp`` for ``gvn_tools.transport.Http``;
5
+ ``FakeMcpServer`` (a scripted tool listing, scripted results per tool, records calls) for
6
+ ``gvn_tools.protocol.McpServer``.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import copy
12
+ import pathlib
13
+ import typing
14
+
15
+ from gvn_tools.process import Commands, Completed, check_run
16
+ from gvn_tools.protocol import McpResult, McpServer, ToolListing, check_call
17
+ from gvn_tools.transport import Http, Response, check_request
18
+
19
+ if typing.TYPE_CHECKING:
20
+ from collections.abc import Iterable, Mapping, Sequence
21
+
22
+ # --------------------------------------------------------------------------- FakeCommands
23
+
24
+
25
+ class FakeCommands(Commands):
26
+ """A Commands that runs nothing: it answers each argv with what was scripted for it.
27
+
28
+ fake = FakeCommands() # unscripted argv -> LookupError
29
+ fake = FakeCommands(default=Completed(0)) # unscripted argv -> that result
30
+ fake.script(["git", "status"], Completed(0, "clean\\n"))
31
+ fake.script(["make"], Completed(2, errors="boom"), Completed(0)) # in turn
32
+ fake.script(["slow"], TimedOut("killed")) # an exception instance is raised
33
+ await fake.run(["git", "status"], path, 60, 20000)
34
+ fake.calls() # [{"argv": (...), "cwd": Path, "timeout", "limit", "environment"}]
35
+
36
+ ``run`` validates its arguments exactly as ``LocalCommands`` does (TypeError/ValueError)
37
+ and records every valid call, including those that end in a scripted exception. The
38
+ results scripted for one argv are given in turn; the last one repeats. A scripted
39
+ Completed's output and errors are cut at the ``limit`` of the call, as a real run would
40
+ be (``truncated()`` then True). Not safe for use from several threads.
41
+ """
42
+
43
+ def __init__(self, default: Completed | None = None) -> None:
44
+ """``default``: the Completed for an argv nothing was scripted for, or None to raise
45
+ LookupError for it. TypeError otherwise."""
46
+ if default is not None and not isinstance(default, Completed):
47
+ raise TypeError(f"default must be a Completed or None, got {type(default).__name__}")
48
+ self._default = default
49
+ self._scripts = {}
50
+ self._calls = []
51
+
52
+ def script(self, argv: Sequence[str], *results: Completed | BaseException) -> typing.Self:
53
+ """Answer ``argv`` (a list or tuple of str) with ``results`` in turn, the last
54
+ repeating. Each is a Completed or an exception instance to raise. Replaces anything
55
+ scripted for that argv before. Returns this fake. TypeError/ValueError."""
56
+ key, _, _, _, _ = check_run(argv, pathlib.Path("/"), 1, 0)
57
+ if not results:
58
+ raise ValueError("script at least one result")
59
+ for result in results:
60
+ if not isinstance(result, (Completed, BaseException)):
61
+ raise TypeError(
62
+ f"a scripted result is a Completed or an exception, got {type(result).__name__}"
63
+ )
64
+ self._scripts[key] = list(results)
65
+ return self
66
+
67
+ def calls(self) -> list[dict[str, typing.Any]]:
68
+ """A fresh list of every call made, oldest first: dicts with ``argv`` (tuple),
69
+ ``cwd`` (Path), ``timeout``, ``limit`` and ``environment`` (a dict, {} for None)."""
70
+ return [dict(call, environment=dict(call["environment"])) for call in self._calls]
71
+
72
+ async def run(
73
+ self,
74
+ argv: Sequence[str],
75
+ cwd: pathlib.Path,
76
+ timeout: float,
77
+ limit: int,
78
+ environment: Mapping[str, str] | None = None,
79
+ ) -> Completed:
80
+ argv, cwd, timeout, limit, extra = check_run(argv, cwd, timeout, limit, environment)
81
+ self._calls.append(
82
+ {"argv": argv, "cwd": cwd, "timeout": timeout, "limit": limit, "environment": extra}
83
+ )
84
+ queue = self._scripts.get(argv)
85
+ if queue is None:
86
+ if self._default is None:
87
+ raise LookupError(f"FakeCommands has nothing scripted for {list(argv)!r}")
88
+ result = self._default
89
+ else:
90
+ result = queue.pop(0) if len(queue) > 1 else queue[0]
91
+ if isinstance(result, BaseException):
92
+ raise result
93
+ output, errors = result.output(), result.errors()
94
+ if len(output) <= limit and len(errors) <= limit:
95
+ return result
96
+ return Completed(result.code(), output[:limit], errors[:limit], True)
97
+
98
+ def __repr__(self) -> str:
99
+ return f"FakeCommands(scripted={len(self._scripts)}, calls={len(self._calls)})"
100
+
101
+
102
+ # --------------------------------------------------------------------------- FakeHttp
103
+
104
+
105
+ class FakeHttp(Http):
106
+ """An Http that sends nothing: it answers each (method, url) with what was scripted.
107
+
108
+ fake = FakeHttp() # unscripted request -> LookupError
109
+ fake = FakeHttp(default=Response(404)) # unscripted request -> that response
110
+ fake.script("GET", "https://api.example.com/x", Response(200, text="hi"))
111
+ fake.script("POST", url, Response(500), Response(201)) # in turn
112
+ fake.script("GET", url, Unreachable("refused")) # raised when asked
113
+ await fake.send("GET", url, {}, None, 30, 100000)
114
+ fake.requests() # [{"method", "url", "headers", "body", "timeout", "limit"}]
115
+
116
+ ``method`` and ``url`` are matched exactly (the method upper-cased, the URL as a str,
117
+ query and all). ``send`` validates its arguments as ``LocalHttp`` does
118
+ (TypeError/ValueError) and records every valid request, including those answered with
119
+ a scripted exception or LookupError. The responses scripted for one request are given
120
+ in turn; the last one repeats. A scripted Response's text is cut at the ``limit`` of
121
+ the request, as a real exchange would be (``truncated()`` then True). Like the port, it
122
+ never follows a redirect. Not safe for use from several threads.
123
+ """
124
+
125
+ def __init__(self, default: Response | None = None) -> None:
126
+ """``default``: the Response for a request nothing was scripted for, or None to
127
+ raise LookupError for it. TypeError otherwise."""
128
+ if default is not None and not isinstance(default, Response):
129
+ raise TypeError(f"default must be a Response or None, got {type(default).__name__}")
130
+ self._default = default
131
+ self._scripts = {}
132
+ self._requests = []
133
+
134
+ def script(self, method: str, url: str, *responses: Response | BaseException) -> typing.Self:
135
+ """Answer ``method`` ``url`` with ``responses`` in turn, the last repeating. Each is a
136
+ Response or an exception instance to raise. Replaces anything scripted for that
137
+ request before. Returns this fake. TypeError/ValueError."""
138
+ check_request(method, url, {}, None, 1, 0)
139
+ if not responses:
140
+ raise ValueError("script at least one response")
141
+ for response in responses:
142
+ if not isinstance(response, (Response, BaseException)):
143
+ raise TypeError(
144
+ "a scripted response is a Response or an exception, "
145
+ f"got {type(response).__name__}"
146
+ )
147
+ self._scripts[(method.upper(), url)] = list(responses)
148
+ return self
149
+
150
+ def requests(self) -> list[dict[str, typing.Any]]:
151
+ """A fresh list of every request made, oldest first: dicts with ``method``, ``url``,
152
+ ``headers`` (a dict, names lower-cased), ``body``, ``timeout`` and ``limit``."""
153
+ return [dict(each, headers=dict(each["headers"])) for each in self._requests]
154
+
155
+ async def send(
156
+ self,
157
+ method: str,
158
+ url: str,
159
+ headers: Mapping[str, str],
160
+ body: str | None,
161
+ timeout: float,
162
+ limit: int,
163
+ ) -> Response:
164
+ found = check_request(method, url, headers, body, timeout, limit)
165
+ self._requests.append(
166
+ {
167
+ "method": method,
168
+ "url": url,
169
+ "headers": found,
170
+ "body": body,
171
+ "timeout": timeout,
172
+ "limit": limit,
173
+ }
174
+ )
175
+ queue = self._scripts.get((method.upper(), url))
176
+ if queue is None:
177
+ if self._default is None:
178
+ raise LookupError(f"FakeHttp has nothing scripted for {method} {url}")
179
+ response = self._default
180
+ else:
181
+ response = queue.pop(0) if len(queue) > 1 else queue[0]
182
+ if isinstance(response, BaseException):
183
+ raise response
184
+ if len(response.text()) <= limit:
185
+ return response
186
+ return Response(response.status(), response.headers(), response.text()[:limit], True)
187
+
188
+ def __repr__(self) -> str:
189
+ return f"FakeHttp(scripted={len(self._scripts)}, requests={len(self._requests)})"
190
+
191
+
192
+ # --------------------------------------------------------------------------- FakeMcpServer
193
+
194
+
195
+ class FakeMcpServer(McpServer):
196
+ """An McpServer that runs nothing: it lists the tools it was given and answers each call
197
+ with what was scripted for that tool.
198
+
199
+ fake = FakeMcpServer(tools=[ToolListing("add", "Add.", schema)])
200
+ fake = FakeMcpServer(tools=[...], default=McpResult([text("ok")])) # unscripted
201
+ fake.script("add", McpResult([text("3")])) # every call to "add"
202
+ fake.script("add", McpResult([text("no")], failed=True), McpResult([text("3")]))
203
+ fake.script("add", Unavailable("no answer")) # raised when called
204
+ fake.offer(ToolListing("add", "Add.", other_schema)) # the listing changes
205
+ fake.offer(Unavailable("down")) # listing() raises it
206
+ await fake.listing(); await fake.call("add", {"a": 1}, 60)
207
+ fake.calls() # [{"name", "arguments", "timeout", "meta"}]
208
+ fake.listings() # how many times listing() was asked
209
+
210
+ ``call`` validates its arguments as ``LocalMcpServer`` does (TypeError/ValueError) and
211
+ records every valid call, including those that end in a scripted exception. It does not
212
+ check that the tool is listed: a real server may answer a call to a tool it no longer
213
+ lists. A tool nothing was scripted for gets ``default``, or LookupError without one. The
214
+ results scripted for one tool are given in turn; the last one repeats. Not safe for use
215
+ from several threads.
216
+ """
217
+
218
+ def __init__(self, tools: Iterable[ToolListing] = (), default: McpResult | None = None) -> None:
219
+ """``tools``: the ToolListings ``listing()`` answers. ``default``: the McpResult for a
220
+ tool nothing was scripted for, or None to raise LookupError. TypeError/ValueError."""
221
+ if default is not None and not isinstance(default, McpResult):
222
+ raise TypeError(f"default must be an McpResult or None, got {type(default).__name__}")
223
+ self._default = default
224
+ self._listing = ()
225
+ self._scripts = {}
226
+ self._calls = []
227
+ self._listings = 0
228
+ self.offer(*tools)
229
+
230
+ def offer(self, *tools: ToolListing | BaseException) -> typing.Self:
231
+ """From now on ``listing()`` answers these ToolListings (names unique), or, given one
232
+ exception instance instead, raises it. Returns this fake. TypeError/ValueError."""
233
+ if len(tools) == 1 and isinstance(tools[0], BaseException):
234
+ self._listing = tools[0]
235
+ return self
236
+ names = set()
237
+ for tool in tools:
238
+ if not isinstance(tool, ToolListing):
239
+ raise TypeError(f"a listed tool is a ToolListing, got {type(tool).__name__}")
240
+ if tool.name() in names:
241
+ raise ValueError(f"tool {tool.name()!r} listed twice")
242
+ names.add(tool.name())
243
+ self._listing = tuple(tools)
244
+ return self
245
+
246
+ def script(self, name: str, *results: McpResult | BaseException) -> typing.Self:
247
+ """Answer calls to tool ``name`` with ``results`` in turn, the last repeating. Each is
248
+ an McpResult or an exception instance to raise. Replaces anything scripted for that
249
+ tool before. Returns this fake. TypeError/ValueError."""
250
+ check_call(name, {}, 1)
251
+ if not results:
252
+ raise ValueError("script at least one result")
253
+ for result in results:
254
+ if not isinstance(result, (McpResult, BaseException)):
255
+ raise TypeError(
256
+ "a scripted result is an McpResult or an exception, "
257
+ f"got {type(result).__name__}"
258
+ )
259
+ self._scripts[name] = list(results)
260
+ return self
261
+
262
+ def calls(self) -> list[dict[str, typing.Any]]:
263
+ """A fresh list of every call made, oldest first: dicts with ``name``, ``arguments``
264
+ (a plain dict), ``timeout`` and ``meta`` (the request's extra ``_meta``, {} for none)."""
265
+ return [
266
+ dict(each, arguments=copy.deepcopy(each["arguments"]), meta=copy.deepcopy(each["meta"]))
267
+ for each in self._calls
268
+ ]
269
+
270
+ def listings(self) -> int:
271
+ """How many times ``listing()`` was asked."""
272
+ return self._listings
273
+
274
+ async def listing(self) -> tuple[ToolListing, ...]:
275
+ self._listings += 1
276
+ if isinstance(self._listing, BaseException):
277
+ raise self._listing
278
+ return self._listing
279
+
280
+ async def call(
281
+ self,
282
+ name: str,
283
+ arguments: Mapping[str, typing.Any],
284
+ timeout: float,
285
+ meta: Mapping[str, typing.Any] | None = None,
286
+ ) -> McpResult:
287
+ plain, extra = check_call(name, arguments, timeout, meta)
288
+ self._calls.append({"name": name, "arguments": plain, "timeout": timeout, "meta": extra})
289
+ queue = self._scripts.get(name)
290
+ if queue is None:
291
+ if self._default is None:
292
+ raise LookupError(f"FakeMcpServer has nothing scripted for {name!r}")
293
+ result = self._default
294
+ else:
295
+ result = queue.pop(0) if len(queue) > 1 else queue[0]
296
+ if isinstance(result, BaseException):
297
+ raise result
298
+ return result
299
+
300
+ def __repr__(self) -> str:
301
+ listed = 0 if isinstance(self._listing, BaseException) else len(self._listing)
302
+ return f"FakeMcpServer(tools={listed}, calls={len(self._calls)})"