gcf-python 2.6.0__py3-none-any.whl → 2.7.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
gcf/__init__.py CHANGED
@@ -102,4 +102,4 @@ __all__ = [
102
102
  "DEFAULT_REANCHOR_N",
103
103
  ]
104
104
 
105
- __version__ = "2.6.0"
105
+ __version__ = "2.7.1"
gcf/decode_generic.py CHANGED
@@ -171,7 +171,7 @@ def _parse_object_body(
171
171
 
172
172
  # Inline array (e.g. items[3]: a,b,c). Only reached if no = found.
173
173
  if not content.startswith("@") and not content.startswith("##"):
174
- bracket_idx = content.find("[")
174
+ bracket_idx = _find_array_bracket(content)
175
175
  if bracket_idx > 0:
176
176
  rest = content[bracket_idx:]
177
177
  close_idx = rest.find("]")
@@ -196,6 +196,26 @@ def _parse_object_body(
196
196
  return i - start
197
197
 
198
198
 
199
+ def _find_array_bracket(s: str) -> int:
200
+ """Index of the '[' that opens a named-array marker (``key[N]: ...``).
201
+
202
+ A quoted key is scanned first so a '[' inside the key name is not mistaken
203
+ for the array bracket (bare keys cannot contain '['). Returns -1 when the
204
+ key is a quoted string not immediately followed by '['.
205
+ """
206
+ if s and s[0] == '"':
207
+ i = 1
208
+ while i < len(s):
209
+ if s[i] == "\\":
210
+ i += 2
211
+ continue
212
+ if s[i] == '"':
213
+ return i + 1 if i + 1 < len(s) and s[i + 1] == "[" else -1
214
+ i += 1
215
+ return -1
216
+ return s.find("[")
217
+
218
+
199
219
  def _find_kv_split(s: str) -> int:
200
220
  if not s:
201
221
  return -1
gcf/fastmcp.py ADDED
@@ -0,0 +1,142 @@
1
+ """Optional FastMCP middleware for opt-in GCF response encoding.
2
+
3
+ This is a small integration helper for `FastMCP <https://gofastmcp.com>`_ servers.
4
+ It requires the ``fastmcp`` extra; the core ``gcf`` package stays
5
+ zero-dependency::
6
+
7
+ pip install "gcf-python[fastmcp]"
8
+
9
+ Register it once on a FastMCP server::
10
+
11
+ from gcf.fastmcp import GcfResponseMiddleware
12
+
13
+ mcp.add_middleware(GcfResponseMiddleware())
14
+
15
+ When ``RESPONSE_FORMAT=gcf`` is set in the environment, each tool result whose
16
+ model-facing content is a single JSON text block is re-encoded as a GCF generic
17
+ wire, so the response uses fewer tokens when it crosses the LLM boundary. It is:
18
+
19
+ - **Opt-in** — nothing changes unless ``RESPONSE_FORMAT=gcf`` is set (or
20
+ ``enabled=True`` is passed).
21
+ - **Never-grow** — GCF is used only when the wire is actually smaller than the
22
+ JSON it would replace; a small result is never enlarged.
23
+ - **Lossless and fail-safe** — the wire must decode back to the same value, and
24
+ on any encoding error the original result is returned, so a tool call is never
25
+ grown, dropped, or garbled over formatting.
26
+ - **Non-destructive** — only a lone JSON text block is re-encoded; a result
27
+ carrying an image or any second block is left untouched, and the tool's
28
+ ``structuredContent`` (if any) is preserved so output-schema validation and
29
+ non-model clients keep receiving JSON.
30
+ """
31
+
32
+ from __future__ import annotations
33
+
34
+ import json
35
+ import logging
36
+ import os
37
+ from typing import Any, Optional
38
+
39
+ try:
40
+ from fastmcp.server.middleware import CallNext, Middleware, MiddlewareContext
41
+ from fastmcp.tools.tool import ToolResult
42
+ from mcp.types import TextContent
43
+ except ImportError as exc: # pragma: no cover - exercised only without the extra
44
+ raise ImportError(
45
+ "gcf.fastmcp requires the optional 'fastmcp' dependency: "
46
+ 'pip install "gcf-python[fastmcp]"'
47
+ ) from exc
48
+
49
+ from .decode_generic import decode_generic
50
+ from .generic import encode_generic
51
+
52
+ logger = logging.getLogger(__name__)
53
+
54
+ DEFAULT_ENV_VAR = "RESPONSE_FORMAT"
55
+
56
+
57
+ def gcf_response_enabled(env_var: str = DEFAULT_ENV_VAR) -> bool:
58
+ """Return True when ``env_var`` is set to ``gcf`` in the environment."""
59
+ return os.environ.get(env_var, "").strip().lower() == "gcf"
60
+
61
+
62
+ class GcfResponseMiddleware(Middleware):
63
+ """FastMCP middleware that re-encodes JSON tool results as GCF, opt-in.
64
+
65
+ Args:
66
+ env_var: Environment variable that gates encoding. Defaults to
67
+ ``RESPONSE_FORMAT``; encoding is on when its value is ``gcf``.
68
+ enabled: Force encoding on or off, bypassing the environment gate.
69
+ ``None`` (the default) reads the environment on each call.
70
+ """
71
+
72
+ def __init__(
73
+ self,
74
+ *,
75
+ env_var: str = DEFAULT_ENV_VAR,
76
+ enabled: Optional[bool] = None,
77
+ ) -> None:
78
+ self._env_var = env_var
79
+ self._enabled = enabled
80
+
81
+ def _is_enabled(self) -> bool:
82
+ if self._enabled is not None:
83
+ return self._enabled
84
+ return gcf_response_enabled(self._env_var)
85
+
86
+ async def on_call_tool(
87
+ self,
88
+ context: "MiddlewareContext",
89
+ call_next: "CallNext",
90
+ ) -> "ToolResult":
91
+ result = await call_next(context)
92
+
93
+ if not self._is_enabled():
94
+ return result
95
+
96
+ payload = _json_payload(result)
97
+ if payload is None:
98
+ return result
99
+
100
+ # _json_payload guarantees exactly one text block, so this is the JSON text
101
+ # the client would otherwise receive.
102
+ original = result.content[0].text
103
+
104
+ try:
105
+ wire = encode_generic(payload)
106
+ # Never-grow: only replace the JSON when GCF is actually smaller, so a
107
+ # small result is never enlarged.
108
+ if len(wire) >= len(original):
109
+ return result
110
+ # Verify the wire decodes back to the same value before shipping it, so a
111
+ # result is never replaced with an unparseable or lossy encoding.
112
+ if decode_generic(wire) != payload:
113
+ return result
114
+ except Exception as exc: # noqa: BLE001 - liveness over correctness of format
115
+ logger.debug("GCF encoding skipped: %s", exc)
116
+ return result
117
+
118
+ return ToolResult(
119
+ content=[TextContent(type="text", text=wire)],
120
+ structured_content=result.structured_content,
121
+ )
122
+
123
+
124
+ def _json_payload(result: "ToolResult") -> Optional[Any]:
125
+ """The JSON value to encode, or None if the result is not a single JSON body.
126
+
127
+ Only a result whose content is exactly one text block is re-encoded, so an
128
+ image or other block sent alongside it is never dropped. ``structuredContent``
129
+ (the tool's typed value) is preferred as the payload; otherwise the lone text
130
+ block is parsed as JSON.
131
+ """
132
+ content = result.content or []
133
+ if len(content) != 1 or not isinstance(content[0], TextContent):
134
+ return None
135
+
136
+ if result.structured_content is not None:
137
+ return result.structured_content
138
+
139
+ try:
140
+ return json.loads(content[0].text)
141
+ except (json.JSONDecodeError, ValueError):
142
+ return None
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: gcf-python
3
- Version: 2.6.0
3
+ Version: 2.7.1
4
4
  Summary: The AI-native wire format for structured data. 50-92% fewer tokens than JSON, with multi-turn delta encoding for agent loops. 100% comprehension on every frontier model. Zero dependencies.
5
5
  Project-URL: Homepage, https://github.com/blackwell-systems/gcf-python
6
6
  Project-URL: Documentation, https://gcformat.com/
@@ -21,6 +21,8 @@ Classifier: Programming Language :: Python :: 3.13
21
21
  Classifier: Topic :: Software Development :: Libraries
22
22
  Classifier: Typing :: Typed
23
23
  Requires-Python: >=3.9
24
+ Provides-Extra: fastmcp
25
+ Requires-Dist: fastmcp>=2.11.0; extra == 'fastmcp'
24
26
  Description-Content-Type: text/markdown
25
27
 
26
28
  <p align="center">
@@ -244,6 +246,22 @@ for snapshot in stream: # each turn's current GenericSet
244
246
 
245
247
  `fixed_n(15)` re-anchors every N turns; `size_guard()` (recommended) re-anchors once the cumulative delta reaches a full payload's size. It introduces no new wire syntax and the decoder stays cadence-agnostic, so a re-anchor is just the protocol's "full" outcome on a schedule.
246
248
 
249
+ ## FastMCP middleware
250
+
251
+ A drop-in middleware for [FastMCP](https://gofastmcp.com) servers that re-encodes JSON tool results as GCF, opt-in. It requires the `fastmcp` extra (the core package stays zero-dependency):
252
+
253
+ ```bash
254
+ pip install "gcf-python[fastmcp]"
255
+ ```
256
+
257
+ ```python
258
+ from gcf.fastmcp import GcfResponseMiddleware
259
+
260
+ mcp.add_middleware(GcfResponseMiddleware())
261
+ ```
262
+
263
+ When `RESPONSE_FORMAT=gcf` is set in the environment, each tool result whose model-facing content is a single JSON text block is returned as a GCF generic wire instead of JSON. It is opt-in (nothing changes unless the variable is set), lossless and fail-safe (on any encoding error the original result is returned), and non-destructive: only a lone JSON text block is re-encoded, and the tool's `structuredContent` is preserved so output-schema validation and non-model clients keep receiving JSON.
264
+
247
265
  ## API
248
266
 
249
267
  | Function | Description |
@@ -304,7 +322,7 @@ GCF wins 15/16 datasets on the expanded [token efficiency benchmark](https://git
304
322
 
305
323
  **Zero runtime dependencies. Permanently.** All six implementations depend only on their language's standard library. No transitive dependencies. No supply chain risk. This is a permanent commitment: GCF will never take on external runtime dependencies. MIT licensed. All implementations support both generic profile (`encodeGeneric`) and graph profile (`encode`). CLI included in all 6 languages.
306
324
 
307
- **Specification:** [SPEC v3.5.2 Stable](https://github.com/blackwell-systems/gcf/blob/main/SPEC.md) with 269 conformance fixtures, 43,000,000,000+ lossless round-trips verified across 5 formats and 6 languages. Current versions: Go v1.6.2, TypeScript v2.5.2, Python v2.5.3, Rust v2.5.3, Swift v2.6.2, Kotlin v2.5.2, .NET v0.1.2. Cross-language conformance verified across all seven SDKs.
325
+ **Specification:** [SPEC v3.5.3 Stable](https://github.com/blackwell-systems/gcf/blob/main/SPEC.md) with 281 conformance fixtures, 43,000,000,000+ lossless round-trips verified across 5 formats and 6 languages. Current versions: Go v1.7.1, TypeScript v2.6.1, Python v2.7.0, Rust v3.0.1, Swift v2.7.1, Kotlin v2.6.1, .NET v0.2.1. Cross-language conformance verified across all seven SDKs.
308
326
 
309
327
  ## Adopted by
310
328
 
@@ -1,11 +1,12 @@
1
- gcf/__init__.py,sha256=QRGOX87aJR1RXZktNnzRgYbqM7Fp9i1ZPIAf97wE-o8,2616
1
+ gcf/__init__.py,sha256=uRYqyGTFSlmnfoj0hh79AZ_KhxiCgZgJt_v-okiK4_k,2616
2
2
  gcf/__main__.py,sha256=EpvBz1yc8H0D5OJ1zy2tYke-kRzvudKa4DEbfeW14ao,71
3
3
  gcf/cli.py,sha256=UEe1CAZn-rKGNIo_ap8-oez3ucl6DSRbsdv6RDnzygY,5256
4
4
  gcf/constants.py,sha256=cmZ8YJSOB0im_eyfN8v4UvrLpBC6Fuf4cfcKZGbutxY,638
5
5
  gcf/decode.py,sha256=TP58_7UBhfeI0o9zpNgtQvAnLQGhNt0RaUjku7Ke75A,7162
6
- gcf/decode_generic.py,sha256=OTNhryeAFfE5izpP6dD0DtBzcC_Jht1-vLg51gjnZ28,30510
6
+ gcf/decode_generic.py,sha256=X59J2tV_ybZdWupVIVRtfLiqdxko2wfIn78Kkm5lNls,31170
7
7
  gcf/delta.py,sha256=oviQ9WsDRYXPXE8bw6SFutmzMRIvu-U_Zzw-39Nd5Ic,8053
8
8
  gcf/encode.py,sha256=OYGDyF3oP2I8Y2PrPL_5yDVURqB0mghtqlOGyDEd-Fs,4081
9
+ gcf/fastmcp.py,sha256=cwIX77DhA96rMrelQcrlAlFXGQ4FDNModa4rSGlGN7I,5139
9
10
  gcf/generic.py,sha256=1c53utF2GcD8lS_wks2opQw08hMz4KGL-7C8g7JB5bA,21577
10
11
  gcf/generic_delta.py,sha256=5KSUT_QUeH7OILLWfu9JveaXRSrqRIi3c6E8WjlgC4Q,18785
11
12
  gcf/keyed_map.py,sha256=qCwhehXB1FQ2iYCPhcvXOqGwrVqdXhGYZGxv56CSUgc,3644
@@ -15,8 +16,8 @@ gcf/session.py,sha256=rPqR4xsHKpi_G37t1ODwkTUdHhVAGa3Uig8F60h34Ms,5335
15
16
  gcf/stream.py,sha256=3eyzmLMZPyEGC1MS9pujxio2x_t7rCL-eNuJ4DjYkaA,5938
16
17
  gcf/stream_generic.py,sha256=h2mJ-jI-c1H2L0uoQVhrvDc7uJEcOwS1MB51k4SCPNM,5775
17
18
  gcf/types.py,sha256=AWm-LQoSqLHAYtEjcAxWQZqJ4JXqNreLUKO2mJFgNMA,1465
18
- gcf_python-2.6.0.dist-info/METADATA,sha256=0iJSJoi00y_XFo6x3cM7lq5mp9JuShcf3VFfCYYbov4,16165
19
- gcf_python-2.6.0.dist-info/WHEEL,sha256=zOwg4jB6zX2kU910N-cMawjivD6tO8NEWvE12je1bVk,87
20
- gcf_python-2.6.0.dist-info/entry_points.txt,sha256=aFT6gqlkh8iGfM8cblE-LUMxHH08_v71IIoZtDdRIVA,37
21
- gcf_python-2.6.0.dist-info/licenses/LICENSE,sha256=2Fit9wnaIe--RMSAgyQqxC5hfZTyZqn4fIdBtp9qPDw,1072
22
- gcf_python-2.6.0.dist-info/RECORD,,
19
+ gcf_python-2.7.1.dist-info/METADATA,sha256=FYQP8X41OUkaB4Bwyvl0rvUCmlMsdTfINUDiRqQMcLM,17107
20
+ gcf_python-2.7.1.dist-info/WHEEL,sha256=zOwg4jB6zX2kU910N-cMawjivD6tO8NEWvE12je1bVk,87
21
+ gcf_python-2.7.1.dist-info/entry_points.txt,sha256=aFT6gqlkh8iGfM8cblE-LUMxHH08_v71IIoZtDdRIVA,37
22
+ gcf_python-2.7.1.dist-info/licenses/LICENSE,sha256=2Fit9wnaIe--RMSAgyQqxC5hfZTyZqn4fIdBtp9qPDw,1072
23
+ gcf_python-2.7.1.dist-info/RECORD,,