llm-refract 0.1.2__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.
- llm_refract-0.1.2/.gitignore +25 -0
- llm_refract-0.1.2/LICENSE +201 -0
- llm_refract-0.1.2/PKG-INFO +59 -0
- llm_refract-0.1.2/README.md +39 -0
- llm_refract-0.1.2/pyproject.toml +35 -0
- llm_refract-0.1.2/src/refract/__init__.py +230 -0
- llm_refract-0.1.2/src/refract/artifact.py +36 -0
- llm_refract-0.1.2/src/refract/integrations/__init__.py +1 -0
- llm_refract-0.1.2/src/refract/integrations/manual.py +33 -0
- llm_refract-0.1.2/src/refract/py.typed +0 -0
- llm_refract-0.1.2/src/refract_mcp/__init__.py +1 -0
- llm_refract-0.1.2/src/refract_mcp/__main__.py +3 -0
- llm_refract-0.1.2/src/refract_mcp/py.typed +0 -0
- llm_refract-0.1.2/src/refract_mcp/server.py +145 -0
- llm_refract-0.1.2/tests/test_artifact.py +22 -0
- llm_refract-0.1.2/tests/test_mcp.py +63 -0
- llm_refract-0.1.2/tests/test_recording.py +53 -0
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/target/
|
|
2
|
+
/.cache/
|
|
3
|
+
/.venv/
|
|
4
|
+
node_modules/
|
|
5
|
+
dist/
|
|
6
|
+
__pycache__/
|
|
7
|
+
.pytest_cache/
|
|
8
|
+
.ruff_cache/
|
|
9
|
+
*.egg-info/
|
|
10
|
+
*.db
|
|
11
|
+
*.db-shm
|
|
12
|
+
*.db-wal
|
|
13
|
+
.env
|
|
14
|
+
.env.*
|
|
15
|
+
!.env.example
|
|
16
|
+
/test-results/
|
|
17
|
+
/playwright-report/
|
|
18
|
+
|
|
19
|
+
/*.rfr
|
|
20
|
+
/refract-report.json
|
|
21
|
+
/docs/architecture/product-vision.md
|
|
22
|
+
|
|
23
|
+
/.examples/
|
|
24
|
+
/apps/viewer/test-results/
|
|
25
|
+
/apps/viewer/playwright-report/
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: llm-refract
|
|
3
|
+
Version: 0.1.2
|
|
4
|
+
Summary: Provider-neutral Python instrumentation, portable execution artifacts, and an MCP interface for the Refract execution engine.
|
|
5
|
+
Project-URL: Repository, https://github.com/khaleddeissa/llm-refract
|
|
6
|
+
Project-URL: Documentation, https://github.com/khaleddeissa/llm-refract/tree/main/docs
|
|
7
|
+
Project-URL: Issues, https://github.com/khaleddeissa/llm-refract/issues
|
|
8
|
+
License-Expression: Apache-2.0
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Keywords: ai,execution,mcp,observability,replay
|
|
11
|
+
Classifier: Development Status :: 3 - Alpha
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
15
|
+
Classifier: Typing :: Typed
|
|
16
|
+
Requires-Python: >=3.11
|
|
17
|
+
Provides-Extra: mcp
|
|
18
|
+
Requires-Dist: mcp<2,>=1.26; extra == 'mcp'
|
|
19
|
+
Description-Content-Type: text/markdown
|
|
20
|
+
|
|
21
|
+
# llm-refract
|
|
22
|
+
|
|
23
|
+
Provider-neutral Python instrumentation for AI applications, plus an optional MCP interface to the
|
|
24
|
+
Refract execution engine. Export portable `.rfr` files or submit snapshots to the Refract REST service.
|
|
25
|
+
|
|
26
|
+
## Install
|
|
27
|
+
|
|
28
|
+
```bash
|
|
29
|
+
pip install llm-refract
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
MCP support is an optional extra:
|
|
33
|
+
|
|
34
|
+
```bash
|
|
35
|
+
pip install "llm-refract[mcp]"
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
## SDK usage
|
|
39
|
+
|
|
40
|
+
```python
|
|
41
|
+
import refract
|
|
42
|
+
|
|
43
|
+
with refract.run("agent", path="run.rfr"):
|
|
44
|
+
refract.event(type="generation", name="answer", output={"text": "Hello"})
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
See the [usage guide](https://github.com/khaleddeissa/llm-refract/blob/main/docs/usage/python.md).
|
|
48
|
+
|
|
49
|
+
## MCP server
|
|
50
|
+
|
|
51
|
+
Executable stdio interface to the Rust Refract API: ten read-only tools, plus import/fork tools when
|
|
52
|
+
`REFRACT_MCP_ALLOW_WRITES=1`. Requires the `mcp` extra above. Start with:
|
|
53
|
+
|
|
54
|
+
```bash
|
|
55
|
+
refract-mcp
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
See [configuration, tool inventory and limits](https://github.com/khaleddeissa/llm-refract/blob/main/docs/usage/mcp.md).
|
|
59
|
+
Implementation: [server.py](src/refract_mcp/server.py).
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
# llm-refract
|
|
2
|
+
|
|
3
|
+
Provider-neutral Python instrumentation for AI applications, plus an optional MCP interface to the
|
|
4
|
+
Refract execution engine. Export portable `.rfr` files or submit snapshots to the Refract REST service.
|
|
5
|
+
|
|
6
|
+
## Install
|
|
7
|
+
|
|
8
|
+
```bash
|
|
9
|
+
pip install llm-refract
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
MCP support is an optional extra:
|
|
13
|
+
|
|
14
|
+
```bash
|
|
15
|
+
pip install "llm-refract[mcp]"
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
## SDK usage
|
|
19
|
+
|
|
20
|
+
```python
|
|
21
|
+
import refract
|
|
22
|
+
|
|
23
|
+
with refract.run("agent", path="run.rfr"):
|
|
24
|
+
refract.event(type="generation", name="answer", output={"text": "Hello"})
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
See the [usage guide](https://github.com/khaleddeissa/llm-refract/blob/main/docs/usage/python.md).
|
|
28
|
+
|
|
29
|
+
## MCP server
|
|
30
|
+
|
|
31
|
+
Executable stdio interface to the Rust Refract API: ten read-only tools, plus import/fork tools when
|
|
32
|
+
`REFRACT_MCP_ALLOW_WRITES=1`. Requires the `mcp` extra above. Start with:
|
|
33
|
+
|
|
34
|
+
```bash
|
|
35
|
+
refract-mcp
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
See [configuration, tool inventory and limits](https://github.com/khaleddeissa/llm-refract/blob/main/docs/usage/mcp.md).
|
|
39
|
+
Implementation: [server.py](src/refract_mcp/server.py).
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling>=1.27"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "llm-refract"
|
|
7
|
+
version = "0.1.2"
|
|
8
|
+
description = "Provider-neutral Python instrumentation, portable execution artifacts, and an MCP interface for the Refract execution engine."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.11"
|
|
11
|
+
license = "Apache-2.0"
|
|
12
|
+
license-files = ["LICENSE"]
|
|
13
|
+
keywords = ["ai", "execution", "replay", "observability", "mcp"]
|
|
14
|
+
classifiers = [
|
|
15
|
+
"Development Status :: 3 - Alpha",
|
|
16
|
+
"Programming Language :: Python :: 3",
|
|
17
|
+
"Programming Language :: Python :: 3.11",
|
|
18
|
+
"Programming Language :: Python :: 3.12",
|
|
19
|
+
"Typing :: Typed",
|
|
20
|
+
]
|
|
21
|
+
dependencies = []
|
|
22
|
+
|
|
23
|
+
[project.optional-dependencies]
|
|
24
|
+
mcp = ["mcp>=1.26,<2"]
|
|
25
|
+
|
|
26
|
+
[project.scripts]
|
|
27
|
+
refract-mcp = "refract_mcp.server:main"
|
|
28
|
+
|
|
29
|
+
[project.urls]
|
|
30
|
+
Repository = "https://github.com/khaleddeissa/llm-refract"
|
|
31
|
+
Documentation = "https://github.com/khaleddeissa/llm-refract/tree/main/docs"
|
|
32
|
+
Issues = "https://github.com/khaleddeissa/llm-refract/issues"
|
|
33
|
+
|
|
34
|
+
[tool.hatch.build.targets.wheel]
|
|
35
|
+
packages = ["src/refract", "src/refract_mcp"]
|
|
@@ -0,0 +1,230 @@
|
|
|
1
|
+
"""Manual, provider-neutral instrumentation with local recording by default."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import contextvars
|
|
6
|
+
import copy
|
|
7
|
+
import functools
|
|
8
|
+
import inspect
|
|
9
|
+
import json
|
|
10
|
+
import time
|
|
11
|
+
import urllib.request
|
|
12
|
+
import uuid
|
|
13
|
+
from datetime import UTC, datetime
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
from typing import Any, Self
|
|
16
|
+
|
|
17
|
+
from .artifact import pack
|
|
18
|
+
|
|
19
|
+
SPEC_VERSION = "refract.execution.v1"
|
|
20
|
+
_current: contextvars.ContextVar[Run | None] = contextvars.ContextVar("refract_run", default=None)
|
|
21
|
+
_TYPES = {
|
|
22
|
+
"generation",
|
|
23
|
+
"tool.call",
|
|
24
|
+
"retrieval",
|
|
25
|
+
"decision",
|
|
26
|
+
"state.change",
|
|
27
|
+
"checkpoint",
|
|
28
|
+
"handoff",
|
|
29
|
+
"human",
|
|
30
|
+
"artifact",
|
|
31
|
+
"error",
|
|
32
|
+
}
|
|
33
|
+
_POLICIES = {"READ_ONLY", "MOCK", "RECORDED", "LIVE", "REQUIRES_APPROVAL", "BLOCKED"}
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _now() -> str:
|
|
37
|
+
return datetime.now(UTC).isoformat()
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _redact(value: Any) -> Any:
|
|
41
|
+
if isinstance(value, dict):
|
|
42
|
+
return {
|
|
43
|
+
k: "[REDACTED]"
|
|
44
|
+
if any(
|
|
45
|
+
s in k.lower().replace("-", "_")
|
|
46
|
+
for s in (
|
|
47
|
+
"password",
|
|
48
|
+
"secret",
|
|
49
|
+
"token",
|
|
50
|
+
"api_key",
|
|
51
|
+
"authorization",
|
|
52
|
+
"cookie",
|
|
53
|
+
"email",
|
|
54
|
+
)
|
|
55
|
+
)
|
|
56
|
+
else _redact(v)
|
|
57
|
+
for k, v in value.items()
|
|
58
|
+
}
|
|
59
|
+
if isinstance(value, list):
|
|
60
|
+
return [_redact(v) for v in value]
|
|
61
|
+
return value
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _snapshot(value: Any) -> Any:
|
|
65
|
+
return _redact(json.loads(json.dumps(value, allow_nan=False)))
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
class Run:
|
|
69
|
+
def __init__(
|
|
70
|
+
self,
|
|
71
|
+
name: str,
|
|
72
|
+
*,
|
|
73
|
+
path: str | Path | None = None,
|
|
74
|
+
metadata: dict | None = None,
|
|
75
|
+
endpoint: str | None = None,
|
|
76
|
+
):
|
|
77
|
+
if not name.strip():
|
|
78
|
+
raise ValueError("run name cannot be empty")
|
|
79
|
+
self.path, self.endpoint = path, endpoint
|
|
80
|
+
self.data: dict[str, Any] = {
|
|
81
|
+
"spec_version": SPEC_VERSION,
|
|
82
|
+
"id": f"run_{uuid.uuid4()}",
|
|
83
|
+
"name": name,
|
|
84
|
+
"status": "running",
|
|
85
|
+
"started_at": _now(),
|
|
86
|
+
"ended_at": None,
|
|
87
|
+
"metadata": _snapshot(metadata or {}),
|
|
88
|
+
"events": [],
|
|
89
|
+
}
|
|
90
|
+
self._active = False
|
|
91
|
+
|
|
92
|
+
def __enter__(self) -> Self:
|
|
93
|
+
if self._active or self.data["status"] != "running":
|
|
94
|
+
raise RuntimeError("run contexts are single-use")
|
|
95
|
+
self._active = True
|
|
96
|
+
self._token = _current.set(self)
|
|
97
|
+
return self
|
|
98
|
+
|
|
99
|
+
def __exit__(self, exc_type, exc, tb) -> None:
|
|
100
|
+
try:
|
|
101
|
+
if exc is not None:
|
|
102
|
+
self.event(
|
|
103
|
+
type="error",
|
|
104
|
+
name=type(exc).__name__,
|
|
105
|
+
status="failed",
|
|
106
|
+
output={"exception_type": type(exc).__name__},
|
|
107
|
+
)
|
|
108
|
+
self.data["status"] = "failed" if exc is not None else "completed"
|
|
109
|
+
self.data["ended_at"] = _now()
|
|
110
|
+
if self.path:
|
|
111
|
+
self.export(self.path)
|
|
112
|
+
if self.endpoint:
|
|
113
|
+
self.send(self.endpoint)
|
|
114
|
+
except Exception as recording_error:
|
|
115
|
+
if exc is None:
|
|
116
|
+
raise
|
|
117
|
+
exc.add_note(f"Refract recording also failed: {type(recording_error).__name__}")
|
|
118
|
+
finally:
|
|
119
|
+
self._active = False
|
|
120
|
+
_current.reset(self._token)
|
|
121
|
+
|
|
122
|
+
def event(
|
|
123
|
+
self,
|
|
124
|
+
*,
|
|
125
|
+
type: str,
|
|
126
|
+
name: str,
|
|
127
|
+
input: Any = None,
|
|
128
|
+
output: Any = None,
|
|
129
|
+
parent_id: str | None = None,
|
|
130
|
+
duration_ms: float = 0,
|
|
131
|
+
attributes: dict | None = None,
|
|
132
|
+
replay_policy: str = "RECORDED",
|
|
133
|
+
status: str = "completed",
|
|
134
|
+
) -> str:
|
|
135
|
+
if not self._active:
|
|
136
|
+
raise RuntimeError("events require an active run")
|
|
137
|
+
if type not in _TYPES or replay_policy not in _POLICIES:
|
|
138
|
+
raise ValueError("unsupported event type or replay policy")
|
|
139
|
+
if status not in {"running", "completed", "failed"} or not name.strip():
|
|
140
|
+
raise ValueError("invalid event name/status")
|
|
141
|
+
if duration_ms < 0:
|
|
142
|
+
raise ValueError("duration must be nonnegative")
|
|
143
|
+
if parent_id and parent_id not in {e["id"] for e in self.data["events"]}:
|
|
144
|
+
raise ValueError("parent must precede child")
|
|
145
|
+
event = _snapshot(
|
|
146
|
+
{
|
|
147
|
+
"id": f"evt_{uuid.uuid4()}",
|
|
148
|
+
"run_id": self.data["id"],
|
|
149
|
+
"parent_id": parent_id,
|
|
150
|
+
"type": type,
|
|
151
|
+
"name": name,
|
|
152
|
+
"timestamp": _now(),
|
|
153
|
+
"duration_ms": duration_ms,
|
|
154
|
+
"status": status,
|
|
155
|
+
"input": input,
|
|
156
|
+
"output": output,
|
|
157
|
+
"attributes": attributes or {},
|
|
158
|
+
"replay_policy": replay_policy,
|
|
159
|
+
}
|
|
160
|
+
)
|
|
161
|
+
self.data["events"].append(event)
|
|
162
|
+
return event["id"]
|
|
163
|
+
|
|
164
|
+
def export(self, path: str | Path) -> None:
|
|
165
|
+
path = Path(path)
|
|
166
|
+
data = _snapshot(self.data)
|
|
167
|
+
body = pack(data) if path.suffix == ".rfr" else json.dumps(data, indent=2).encode()
|
|
168
|
+
with path.open("xb") as target:
|
|
169
|
+
target.write(body)
|
|
170
|
+
|
|
171
|
+
def send(self, endpoint: str) -> None:
|
|
172
|
+
request = urllib.request.Request(
|
|
173
|
+
endpoint.rstrip("/") + "/v1/runs",
|
|
174
|
+
json.dumps(_snapshot(self.data)).encode(),
|
|
175
|
+
{"Content-Type": "application/json"},
|
|
176
|
+
method="POST",
|
|
177
|
+
)
|
|
178
|
+
with urllib.request.urlopen(request, timeout=10) as response:
|
|
179
|
+
response.read()
|
|
180
|
+
|
|
181
|
+
def snapshot(self) -> dict:
|
|
182
|
+
return copy.deepcopy(self.data)
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def run(name: str, **kwargs) -> Run:
|
|
186
|
+
return Run(name, **kwargs)
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def event(**kwargs) -> str:
|
|
190
|
+
current = _current.get()
|
|
191
|
+
if current is None:
|
|
192
|
+
raise RuntimeError("refract.event requires an active refract.run context")
|
|
193
|
+
return current.event(**kwargs)
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def trace(fn=None, *, name: str | None = None):
|
|
197
|
+
"""Trace sync/async entrypoints. Arguments and exception messages are not auto-captured."""
|
|
198
|
+
|
|
199
|
+
def decorate(func):
|
|
200
|
+
if inspect.iscoroutinefunction(func):
|
|
201
|
+
|
|
202
|
+
@functools.wraps(func)
|
|
203
|
+
async def asynchronous(*args, **kwargs):
|
|
204
|
+
with run(name or func.__name__):
|
|
205
|
+
start = time.perf_counter()
|
|
206
|
+
result = await func(*args, **kwargs)
|
|
207
|
+
event(
|
|
208
|
+
type="decision",
|
|
209
|
+
name=func.__name__,
|
|
210
|
+
duration_ms=(time.perf_counter() - start) * 1000,
|
|
211
|
+
)
|
|
212
|
+
return result
|
|
213
|
+
|
|
214
|
+
return asynchronous
|
|
215
|
+
|
|
216
|
+
@functools.wraps(func)
|
|
217
|
+
def synchronous(*args, **kwargs):
|
|
218
|
+
with run(name or func.__name__):
|
|
219
|
+
start = time.perf_counter()
|
|
220
|
+
result = func(*args, **kwargs)
|
|
221
|
+
event(
|
|
222
|
+
type="decision",
|
|
223
|
+
name=func.__name__,
|
|
224
|
+
duration_ms=(time.perf_counter() - start) * 1000,
|
|
225
|
+
)
|
|
226
|
+
return result
|
|
227
|
+
|
|
228
|
+
return synchronous
|
|
229
|
+
|
|
230
|
+
return decorate(fn) if fn else decorate
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
"""Readable, checksummed .rfr text artifacts. Rust also reads legacy ZIP recordings."""
|
|
2
|
+
|
|
3
|
+
import hashlib
|
|
4
|
+
import json
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
MAX_BYTES = 16 * 1024 * 1024
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def pack(run: dict[str, Any]) -> bytes:
|
|
11
|
+
payload = (json.dumps(run, indent=2, ensure_ascii=False, allow_nan=False) + "\n").encode()
|
|
12
|
+
if len(payload) > MAX_BYTES:
|
|
13
|
+
raise ValueError("artifact exceeds size limit")
|
|
14
|
+
header = {
|
|
15
|
+
"format": "refract.artifact.v1",
|
|
16
|
+
"encoding": "json",
|
|
17
|
+
"sha256": hashlib.sha256(payload).hexdigest(),
|
|
18
|
+
}
|
|
19
|
+
return json.dumps(header, separators=(",", ":")).encode() + b"\n" + payload
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def unpack(data: bytes) -> dict[str, Any]:
|
|
23
|
+
if len(data) > MAX_BYTES + 4097:
|
|
24
|
+
raise ValueError("artifact exceeds size limit")
|
|
25
|
+
header_bytes, separator, payload = data.partition(b"\n")
|
|
26
|
+
if not separator or len(header_bytes) > 4096 or len(payload) > MAX_BYTES:
|
|
27
|
+
raise ValueError("invalid artifact size/header")
|
|
28
|
+
header = json.loads(header_bytes)
|
|
29
|
+
if header.get("format") != "refract.artifact.v1" or header.get("encoding") != "json":
|
|
30
|
+
raise ValueError("unsupported artifact profile; use the Rust CLI for legacy ZIP files")
|
|
31
|
+
if header.get("sha256") != hashlib.sha256(payload).hexdigest():
|
|
32
|
+
raise ValueError("checksum mismatch")
|
|
33
|
+
run = json.loads(payload)
|
|
34
|
+
if not isinstance(run, dict) or run.get("spec_version") != "refract.execution.v1":
|
|
35
|
+
raise ValueError("unsupported execution version")
|
|
36
|
+
return run
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Explicit provider-neutral adapters."""
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
"""Provider-neutral adapter for any synchronous callable that returns JSON data."""
|
|
2
|
+
|
|
3
|
+
import time
|
|
4
|
+
from collections.abc import Callable
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
import refract
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def generation(call: Callable[[], Any], *, provider: str, model: str, prompt: Any) -> Any:
|
|
11
|
+
start = time.perf_counter()
|
|
12
|
+
try:
|
|
13
|
+
result = call()
|
|
14
|
+
except Exception as error:
|
|
15
|
+
refract.event(
|
|
16
|
+
type="generation",
|
|
17
|
+
name=f"{provider}/{model}",
|
|
18
|
+
input=prompt,
|
|
19
|
+
output={"exception_type": type(error).__name__},
|
|
20
|
+
status="failed",
|
|
21
|
+
duration_ms=(time.perf_counter() - start) * 1000,
|
|
22
|
+
attributes={"provider": provider, "model": model},
|
|
23
|
+
)
|
|
24
|
+
raise
|
|
25
|
+
refract.event(
|
|
26
|
+
type="generation",
|
|
27
|
+
name=f"{provider}/{model}",
|
|
28
|
+
input=prompt,
|
|
29
|
+
output=result,
|
|
30
|
+
duration_ms=(time.perf_counter() - start) * 1000,
|
|
31
|
+
attributes={"provider": provider, "model": model},
|
|
32
|
+
)
|
|
33
|
+
return result
|
|
File without changes
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Refract MCP server."""
|
|
File without changes
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
"""Read-oriented MCP facade over the Rust REST service; never executes tools."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import os
|
|
5
|
+
import urllib.parse
|
|
6
|
+
import urllib.request
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
from mcp.server.fastmcp import FastMCP
|
|
10
|
+
from mcp.types import ToolAnnotations
|
|
11
|
+
|
|
12
|
+
mcp = FastMCP(
|
|
13
|
+
"refract", instructions="Inspect captured executions. No live execution is supported."
|
|
14
|
+
)
|
|
15
|
+
READ = ToolAnnotations(readOnlyHint=True, destructiveHint=False, openWorldHint=False)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def api(path: str, body: dict | None = None) -> Any:
|
|
19
|
+
endpoint = os.environ.get("REFRACT_SERVER_URL", "http://127.0.0.1:8000").rstrip("/")
|
|
20
|
+
request = urllib.request.Request(
|
|
21
|
+
endpoint + path,
|
|
22
|
+
None if body is None else json.dumps(body).encode(),
|
|
23
|
+
{"Content-Type": "application/json"},
|
|
24
|
+
)
|
|
25
|
+
with urllib.request.urlopen(request, timeout=15) as response:
|
|
26
|
+
data = response.read(17 * 1024 * 1024 + 1)
|
|
27
|
+
if len(data) > 17 * 1024 * 1024:
|
|
28
|
+
raise ValueError("response exceeds size limit")
|
|
29
|
+
return json.loads(data)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def run_path(run_id: str) -> str:
|
|
33
|
+
if not run_id or run_id in {".", ".."}:
|
|
34
|
+
raise ValueError("invalid run id")
|
|
35
|
+
return "/v1/runs/" + urllib.parse.quote(run_id, safe="")
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
@mcp.tool(annotations=READ)
|
|
39
|
+
def search_runs(query: str = "", status: str = "") -> list[dict]:
|
|
40
|
+
"""Search the latest 100 stored snapshots by name/id and optional status."""
|
|
41
|
+
if status not in {"", "running", "completed", "failed"}:
|
|
42
|
+
raise ValueError("unsupported status")
|
|
43
|
+
return [
|
|
44
|
+
r
|
|
45
|
+
for r in api("/v1/runs")
|
|
46
|
+
if query.lower() in (r["name"] + " " + r["id"]).lower()
|
|
47
|
+
and (not status or r["status"] == status)
|
|
48
|
+
]
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
@mcp.tool(annotations=READ)
|
|
52
|
+
def list_failed_runs() -> list[dict]:
|
|
53
|
+
"""Return failed runs among the latest 100 snapshots."""
|
|
54
|
+
return search_runs(status="failed")
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
@mcp.tool(annotations=READ)
|
|
58
|
+
def inspect_run(run_id: str) -> dict:
|
|
59
|
+
"""Read metadata and all recorded events for a run."""
|
|
60
|
+
return api(run_path(run_id))
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
@mcp.tool(annotations=READ)
|
|
64
|
+
def inspect_event(run_id: str, event_id: str) -> dict:
|
|
65
|
+
"""Read one recorded event, including input, output and replay policy."""
|
|
66
|
+
for event in inspect_run(run_id)["events"]:
|
|
67
|
+
if event["id"] == event_id:
|
|
68
|
+
return event
|
|
69
|
+
raise ValueError("event not found")
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
@mcp.tool(annotations=READ)
|
|
73
|
+
def show_execution_graph(run_id: str) -> dict:
|
|
74
|
+
"""Return nodes and parent-child edges in recorded order."""
|
|
75
|
+
events = inspect_run(run_id)["events"]
|
|
76
|
+
return {
|
|
77
|
+
"nodes": [{k: e[k] for k in ("id", "name", "type", "status")} for e in events],
|
|
78
|
+
"edges": [{"from": e["parent_id"], "to": e["id"]} for e in events if e["parent_id"]],
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
@mcp.tool(annotations=READ)
|
|
83
|
+
def compare_runs(left: str, right: str) -> dict:
|
|
84
|
+
"""Compare recorded event semantics; does not execute either run."""
|
|
85
|
+
return api("/v1/diff", {"left": left, "right": right})
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
@mcp.tool(annotations=READ)
|
|
89
|
+
def find_first_divergence(left: str, right: str) -> dict:
|
|
90
|
+
"""Return the first differing event position and its before/after values."""
|
|
91
|
+
result = compare_runs(left, right)
|
|
92
|
+
return {
|
|
93
|
+
"index": result["first_divergence"],
|
|
94
|
+
"difference": next(iter(result["differences"]), None),
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
@mcp.tool(annotations=READ)
|
|
99
|
+
def export_run(run_id: str) -> dict:
|
|
100
|
+
"""Return the canonical snapshot and artifact download path, without writing files."""
|
|
101
|
+
return {"execution": inspect_run(run_id), "artifact_path": run_path(run_id) + "/artifact"}
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
@mcp.resource("refract://capabilities")
|
|
105
|
+
def capabilities() -> str:
|
|
106
|
+
"""Describe this server's supported operations and limits."""
|
|
107
|
+
return json.dumps(
|
|
108
|
+
{
|
|
109
|
+
"transport": "stdio",
|
|
110
|
+
"read_only": os.environ.get("REFRACT_MCP_ALLOW_WRITES") != "1",
|
|
111
|
+
"run_list_limit": 100,
|
|
112
|
+
"live_replay": False,
|
|
113
|
+
"spec_version": "refract.execution.v1",
|
|
114
|
+
}
|
|
115
|
+
)
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def main() -> None:
|
|
119
|
+
mcp.run(transport="stdio")
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
@mcp.tool(annotations=READ)
|
|
123
|
+
def health() -> dict:
|
|
124
|
+
"""Check API readiness and describe the supported storage/replay mode."""
|
|
125
|
+
return {"readiness": api("/v1/ready"), "storage": "sqlite", "replay": "recorded"}
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
@mcp.tool(annotations=READ)
|
|
129
|
+
def replay_recorded(run_id: str) -> dict:
|
|
130
|
+
"""Return captured outputs. Never executes tools/models; BLOCKED policies are enforced."""
|
|
131
|
+
return api(run_path(run_id) + "/replay", {"mode": "exact"})
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
if os.environ.get("REFRACT_MCP_ALLOW_WRITES") == "1":
|
|
135
|
+
WRITE = ToolAnnotations(readOnlyHint=False, destructiveHint=False, openWorldHint=False)
|
|
136
|
+
|
|
137
|
+
@mcp.tool(annotations=WRITE)
|
|
138
|
+
def fork_run(run_id: str, from_event: str) -> dict:
|
|
139
|
+
"""Persist a prefix branch before an event. Does not execute new steps."""
|
|
140
|
+
return api(run_path(run_id) + "/fork", {"from_event": from_event})
|
|
141
|
+
|
|
142
|
+
@mcp.tool(annotations=WRITE)
|
|
143
|
+
def import_run(execution: dict) -> dict:
|
|
144
|
+
"""Store a canonical snapshot through Rust validation/redaction; duplicate IDs conflict."""
|
|
145
|
+
return api("/v1/runs", execution)
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import json
|
|
2
|
+
from pathlib import Path
|
|
3
|
+
|
|
4
|
+
import pytest
|
|
5
|
+
|
|
6
|
+
from refract.artifact import pack, unpack
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def test_text_roundtrip_and_tamper_detection():
|
|
10
|
+
run = json.loads(
|
|
11
|
+
(
|
|
12
|
+
Path(__file__).resolve().parents[3] / "tests/fixtures/simple-run/execution.json"
|
|
13
|
+
).read_text()
|
|
14
|
+
)
|
|
15
|
+
data = pack(run)
|
|
16
|
+
assert data.decode("utf-8").startswith('{"format":')
|
|
17
|
+
assert unpack(data) == run
|
|
18
|
+
assert pack(run) == data
|
|
19
|
+
with pytest.raises(ValueError, match="checksum"):
|
|
20
|
+
unpack(data.replace(b"demo-1", b"demo-2"))
|
|
21
|
+
with pytest.raises(ValueError, match="header"):
|
|
22
|
+
unpack(b"invalid")
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
import json
|
|
3
|
+
import os
|
|
4
|
+
import sys
|
|
5
|
+
from unittest.mock import patch
|
|
6
|
+
|
|
7
|
+
import pytest
|
|
8
|
+
from mcp import ClientSession, StdioServerParameters
|
|
9
|
+
from mcp.client.stdio import stdio_client
|
|
10
|
+
|
|
11
|
+
from refract_mcp import server
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def test_read_tools():
|
|
15
|
+
run = {
|
|
16
|
+
"id": "x",
|
|
17
|
+
"name": "demo",
|
|
18
|
+
"status": "failed",
|
|
19
|
+
"events": [
|
|
20
|
+
{
|
|
21
|
+
"id": "e",
|
|
22
|
+
"name": "lookup",
|
|
23
|
+
"type": "tool.call",
|
|
24
|
+
"status": "failed",
|
|
25
|
+
"parent_id": None,
|
|
26
|
+
}
|
|
27
|
+
],
|
|
28
|
+
}
|
|
29
|
+
with patch.object(server, "api", return_value=[run]):
|
|
30
|
+
assert server.list_failed_runs() == [run]
|
|
31
|
+
assert server.search_runs("missing") == []
|
|
32
|
+
with patch.object(server, "api", return_value=run):
|
|
33
|
+
assert server.inspect_event("x", "e")["name"] == "lookup"
|
|
34
|
+
assert server.show_execution_graph("x")["edges"] == []
|
|
35
|
+
assert server.export_run("x")["artifact_path"] == "/v1/runs/x/artifact"
|
|
36
|
+
assert server.run_path("a/b") == "/v1/runs/a%2Fb"
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
@pytest.mark.parametrize("writes", [False, True])
|
|
40
|
+
def test_real_stdio_handshake_and_discovery(writes):
|
|
41
|
+
async def exercise():
|
|
42
|
+
params = StdioServerParameters(
|
|
43
|
+
command=sys.executable,
|
|
44
|
+
args=["-m", "refract_mcp"],
|
|
45
|
+
env={**os.environ, "REFRACT_MCP_ALLOW_WRITES": "1" if writes else "0"},
|
|
46
|
+
)
|
|
47
|
+
async with stdio_client(params) as (read, write), ClientSession(read, write) as session:
|
|
48
|
+
await session.initialize()
|
|
49
|
+
tools = await session.list_tools()
|
|
50
|
+
assert len(tools.tools) == (12 if writes else 10)
|
|
51
|
+
names = {t.name for t in tools.tools}
|
|
52
|
+
assert ("fork_run" in names) == writes
|
|
53
|
+
assert ("import_run" in names) == writes
|
|
54
|
+
assert "replay_recorded" in names
|
|
55
|
+
assert all(
|
|
56
|
+
t.annotations.readOnlyHint
|
|
57
|
+
for t in tools.tools
|
|
58
|
+
if t.name not in {"fork_run", "import_run"}
|
|
59
|
+
)
|
|
60
|
+
resource = await session.read_resource("refract://capabilities")
|
|
61
|
+
assert json.loads(resource.contents[0].text)["live_replay"] is False
|
|
62
|
+
|
|
63
|
+
asyncio.run(asyncio.wait_for(exercise(), timeout=20))
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
import json
|
|
3
|
+
|
|
4
|
+
import pytest
|
|
5
|
+
|
|
6
|
+
import refract
|
|
7
|
+
from refract.artifact import unpack
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def test_recording_redacts_and_snapshots(tmp_path):
|
|
11
|
+
path = tmp_path / "recording.rfr"
|
|
12
|
+
original = {"email": "private@example.com", "count": 1}
|
|
13
|
+
with refract.run("demo", path=path) as run:
|
|
14
|
+
refract.event(type="generation", name="answer", input=original, output="hello")
|
|
15
|
+
original["count"] = 99
|
|
16
|
+
assert run.data["status"] == "completed"
|
|
17
|
+
event = unpack(path.read_bytes())["events"][0]
|
|
18
|
+
assert event["input"] == {"email": "[REDACTED]", "count": 1}
|
|
19
|
+
with pytest.raises(FileExistsError):
|
|
20
|
+
run.export(path)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def test_failure_resets_context():
|
|
24
|
+
with pytest.raises(ValueError), refract.run("failed") as run:
|
|
25
|
+
raise ValueError("secret message")
|
|
26
|
+
assert run.data["status"] == "failed"
|
|
27
|
+
assert "secret message" not in json.dumps(run.data)
|
|
28
|
+
with pytest.raises(RuntimeError):
|
|
29
|
+
refract.event(type="error", name="outside")
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def test_async_context_isolation():
|
|
33
|
+
async def worker(name):
|
|
34
|
+
with refract.run(name) as run:
|
|
35
|
+
await asyncio.sleep(0)
|
|
36
|
+
refract.event(type="tool.call", name=name)
|
|
37
|
+
return run.snapshot()
|
|
38
|
+
|
|
39
|
+
async def main():
|
|
40
|
+
return await asyncio.gather(worker("a"), worker("b"))
|
|
41
|
+
|
|
42
|
+
runs = asyncio.run(main())
|
|
43
|
+
assert [r["events"][0]["name"] for r in runs] == ["a", "b"]
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def test_decorator_awaits_function():
|
|
47
|
+
@refract.trace
|
|
48
|
+
async def agent():
|
|
49
|
+
await asyncio.sleep(0)
|
|
50
|
+
refract.event(type="decision", name="inside")
|
|
51
|
+
return 42
|
|
52
|
+
|
|
53
|
+
assert asyncio.run(agent()) == 42
|