Skip to content

Commit ff8fb9a

Browse files
authored
feat(ENG-733): support flat_prefixed MCP param style (#192)
* feat(ENG-733): support flat_prefixed MCP param style * test(ENG-733): assert exact pinned mcp endpoint
1 parent 262d518 commit ff8fb9a

3 files changed

Lines changed: 84 additions & 29 deletions

File tree

‎stackone_ai/toolset.py‎

Lines changed: 39 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
import json
88
import logging
99
import os
10+
import re
1011
import threading
1112
from collections.abc import Coroutine, Sequence
1213
from dataclasses import dataclass
@@ -92,6 +93,14 @@ class ExecuteToolsConfig(TypedDict, total=False):
9293
}
9394
_USER_AGENT = f"stackone-ai-python/{_SDK_VERSION}"
9495

96+
# Param-style pinned on the /mcp tool-listing URL. The MCP schema and the RPC-execution unwrap
97+
# (_split_envelope_params) must agree on this, so it is pinned rather than following the server
98+
# default — the server default is free to change without breaking the SDK.
99+
_MCP_PARAM_STYLE = "flat_prefixed"
100+
101+
# Matches a flat_prefixed envelope key: `<location>_<field>` (e.g. `path_id`, `query_limit`).
102+
_FLAT_ENVELOPE_KEY_PATTERN = re.compile(r"^(path|query|body|headers)_(.+)$")
103+
95104

96105
# --- Internal tool_search + tool_execute ---
97106

@@ -444,24 +453,17 @@ def execute(
444453
) -> dict[str, Any]:
445454
parsed_arguments = self._parse_arguments(arguments)
446455

447-
body_payload = self._extract_record(parsed_arguments.pop("body", None))
448-
headers_payload = self._extract_record(parsed_arguments.pop("headers", None))
449-
path_payload = self._extract_record(parsed_arguments.pop("path", None))
450-
query_payload = self._extract_record(parsed_arguments.pop("query", None))
451-
452-
rpc_body: dict[str, Any] = dict(body_payload or {})
453-
for key, value in parsed_arguments.items():
454-
rpc_body[key] = value
456+
envelope = self._split_envelope_params(parsed_arguments)
455457

456458
payload: dict[str, Any] = {
457459
"action": self.name,
458-
"body": rpc_body,
459-
"headers": self._build_action_headers(headers_payload),
460+
"body": envelope["body"],
461+
"headers": self._build_action_headers(envelope["headers"] or None),
460462
}
461-
if path_payload:
462-
payload["path"] = path_payload
463-
if query_payload:
464-
payload["query"] = query_payload
463+
if envelope["path"]:
464+
payload["path"] = envelope["path"]
465+
if envelope["query"]:
466+
payload["query"] = envelope["query"]
465467

466468
return super().execute(payload, options=options)
467469

@@ -477,10 +479,28 @@ def _parse_arguments(self, arguments: str | dict[str, Any] | None) -> dict[str,
477479
return dict(parsed)
478480

479481
@staticmethod
480-
def _extract_record(value: Any) -> dict[str, Any] | None:
481-
if isinstance(value, dict):
482-
return dict(value)
483-
return None
482+
def _split_envelope_params(params: dict[str, Any]) -> dict[str, dict[str, Any]]:
483+
"""Split LLM-supplied tool arguments into the RPC envelope (path/query/headers/body).
484+
485+
Tools are listed with ``?param-style=flat_prefixed``, so keys arrive as
486+
``<location>_<field>`` (for example ``path_id``, ``query_limit``). The prefix carries
487+
the parameter location, so the split needs no per-action schema. A bare dict-valued
488+
``path``/``query``/``headers``/``body`` key is still bucketed for clients holding a
489+
cached nested schema, and any other key falls through to the body.
490+
"""
491+
buckets: dict[str, dict[str, Any]] = {"path": {}, "query": {}, "headers": {}, "body": {}}
492+
for key, value in params.items():
493+
match = _FLAT_ENVELOPE_KEY_PATTERN.match(key)
494+
if match:
495+
location, field = match.group(1), match.group(2)
496+
buckets[location].setdefault(field, value)
497+
continue
498+
if key in ("path", "query", "headers", "body") and isinstance(value, dict):
499+
for field, field_value in value.items():
500+
buckets[key].setdefault(field, field_value)
501+
continue
502+
buckets["body"][key] = value
503+
return buckets
484504

485505
def _build_action_headers(self, additional_headers: dict[str, Any] | None) -> dict[str, str]:
486506
headers: dict[str, str] = {}
@@ -1240,7 +1260,7 @@ def fetch_tools(
12401260
if cached is not None:
12411261
return cached
12421262

1243-
endpoint = f"{self.base_url.rstrip('/')}/mcp"
1263+
endpoint = f"{self.base_url.rstrip('/')}/mcp?param-style={_MCP_PARAM_STYLE}"
12441264

12451265
def _fetch_for_account(account: str | None) -> list[StackOneTool]:
12461266
headers = self._build_mcp_headers(account)

‎tests/test_fetch_tools.py‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -662,3 +662,21 @@ def counting_init(self, tools, hybrid_alpha=None):
662662
toolset.search_tools("bar")
663663

664664
assert build_count["count"] == 2
665+
666+
667+
class TestMcpParamStylePinning:
668+
"""The /mcp listing URL must pin param-style so the schema matches the RPC unwrap."""
669+
670+
def test_fetch_tools_pins_flat_prefixed_param_style(self, monkeypatch):
671+
captured: dict[str, str] = {}
672+
673+
def fake_fetch(endpoint: str, headers: dict[str, str]) -> list[_McpToolDefinition]:
674+
captured["endpoint"] = endpoint
675+
return []
676+
677+
monkeypatch.setattr("stackone_ai.toolset._fetch_mcp_tools", fake_fetch)
678+
679+
toolset = StackOneToolSet(api_key="test-key", base_url="https://api.example.com")
680+
toolset.fetch_tools(account_ids=["acc1"])
681+
682+
assert captured["endpoint"] == "https://api.example.com/mcp?param-style=flat_prefixed"

‎tests/test_tool_calling.py‎

Lines changed: 27 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -327,16 +327,33 @@ def test_parse_arguments_non_dict(self, rpc_tool):
327327
with pytest.raises(ValueError, match="Tool arguments must be a JSON object"):
328328
rpc_tool._parse_arguments("[1, 2, 3]")
329329

330-
def test_extract_record_with_dict(self, rpc_tool):
331-
"""Test _extract_record with dict input"""
332-
result = rpc_tool._extract_record({"key": "value"})
333-
assert result == {"key": "value"}
334-
335-
def test_extract_record_with_non_dict(self, rpc_tool):
336-
"""Test _extract_record with non-dict input"""
337-
assert rpc_tool._extract_record("string") is None
338-
assert rpc_tool._extract_record(123) is None
339-
assert rpc_tool._extract_record(None) is None
330+
def test_split_envelope_params_routes_flat_prefixed_keys(self, rpc_tool):
331+
"""flat_prefixed keys are bucketed into the RPC envelope by their location prefix"""
332+
actual = rpc_tool._split_envelope_params(
333+
{
334+
"path_id": "123",
335+
"query_limit": 10,
336+
"headers_x-custom": "value",
337+
"body_name": "test",
338+
}
339+
)
340+
assert actual["path"] == {"id": "123"}
341+
assert actual["query"] == {"limit": 10}
342+
assert actual["headers"] == {"x-custom": "value"}
343+
assert actual["body"] == {"name": "test"}
344+
345+
def test_split_envelope_params_buckets_nested_and_unprefixed_keys(self, rpc_tool):
346+
"""Bare nested envelopes are accepted and unprefixed keys fall through to the body"""
347+
actual = rpc_tool._split_envelope_params(
348+
{
349+
"body": {"nested": "value"},
350+
"path": {"id": "1"},
351+
"extra": "x",
352+
}
353+
)
354+
assert actual["path"] == {"id": "1"}
355+
assert actual["query"] == {}
356+
assert actual["body"] == {"nested": "value", "extra": "x"}
340357

341358

342359
class TestBinaryDownloadResponse:

0 commit comments

Comments
 (0)