Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .github/workflows/ci.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,10 @@ jobs:
- name: Run Tests
run: uv run pytest

# pyproject allows mcp 1 and 2 and the lockfile pins 2, so the oldest mcp 1 is tested too.
- name: Run Tests against mcp 1
run: uv run --with "mcp==1.30.0" pytest

# Enforces the wire contract in docs/SDK-UCA-CONTRACT.md.
# StackOneHQ/sdk-conformance is private and requires CONFORMANCE_REPO_TOKEN.
# Fork PRs and Dependabot runs cannot access this secret and skip this gate;
Expand Down
3 changes: 2 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,8 @@ dependencies = [
"httpx>=0.28.0",
# fetch_tools() is the only route to a tool and talks MCP, so the client is
# not optional: without it the SDK cannot do anything.
"mcp>=1.30.0,<2.0.0",
# 1.30.0 and 2.2.0 are the first of each major with every published advisory fixed.
"mcp>=1.30.0,!=2.0.*,!=2.1.*,<3.0.0",
]

[project.urls]
Expand Down
245 changes: 133 additions & 112 deletions stackone_ai/tools.py

Large diffs are not rendered by default.

34 changes: 11 additions & 23 deletions stackone_ai/toolset.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,9 @@
_ssl_context,
build_request_headers,
fetch_mcp_tools,
is_end_user_refusal,
is_rate_limited,
is_sdk_owned_header,
retry_for_end_user,
)
from stackone_ai.types import (
DEFAULT_BASE_URL,
Expand Down Expand Up @@ -499,15 +499,12 @@ def _catalog(
def _fetch_for_account(
account: str | None,
) -> list[_Listing]:
without_end_user = account is not None and self._end_user_id(account) is None
try:
listed = fetch_mcp_tools(endpoint, self._build_mcp_headers(account), timeout=self._timeout)
except StackOneAPIError as exc:
# Refused for want of an end user it was sent without: look it up, and retry
# once with it.
if not (without_end_user and account is not None and self._look_up_end_user(account, exc)):
raise
listed = fetch_mcp_tools(endpoint, self._build_mcp_headers(account), timeout=self._timeout)
without_end_user = [account] if account is not None and self._end_user_id(account) is None else []
listed = retry_for_end_user(
lambda: fetch_mcp_tools(endpoint, self._build_mcp_headers(account), timeout=self._timeout),
without_end_user,
self._look_up_end_user,
)
return [(tool_def, account, endpoint) for tool_def in listed]

def _store(catalog: _Catalog) -> None:
Expand Down Expand Up @@ -584,13 +581,7 @@ def _list() -> list[_Listing]:
return [(tool_def, None, endpoint) for tool_def in listed]

without_end_user = [account for account in account_scope if self._end_user_id(account) is None]
try:
listings = _list()
except StackOneAPIError as exc:
refused = next((a for a in without_end_user if is_end_user_refusal(exc, a)), None)
if refused is None or not self._look_up_end_user(refused, exc):
raise
listings = _list()
listings = retry_for_end_user(_list, without_end_user, self._look_up_end_user)

with self._cache_lock:
if generation == self._cache_generation:
Expand Down Expand Up @@ -1019,13 +1010,10 @@ def _look_up_end_user(self, account_id: str, refusal: Exception) -> bool:
"""Given the API's refusal of an account's request for want of its end user, list the
accounts and say whether that one now has an end user recorded to retry with.

Only the API's 400 naming this account counts. A GET /accounts already in flight is
joined rather than another made. If it fails, the refusal is raised with that failure
as its cause: a key without the scope to list accounts would otherwise be told only
that the header does not match.
A GET /accounts already in flight is joined rather than another made. If it fails, the
refusal is raised with that failure as its cause: a key without the scope to list
accounts would otherwise be told only that the header does not match.
"""
if not is_end_user_refusal(refusal, account_id):
return False
try:
self._join_accounts_listing()
except Exception as exc:
Expand Down
68 changes: 29 additions & 39 deletions tests/test_fetch_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,15 @@
import time
from collections.abc import Iterator
from contextlib import asynccontextmanager, contextmanager
from types import SimpleNamespace
from typing import Any
from unittest.mock import AsyncMock, MagicMock, patch

import httpx
import mcp.types as mcp_types
import pytest

from stackone_ai.tools import McpToolDefinition, StackOneMcpTool, fetch_mcp_tools
from stackone_ai.tools import McpToolDefinition, StackOneMcpTool, _mcp_http, fetch_mcp_tools
from stackone_ai.toolset import StackOneToolSet
from stackone_ai.types import (
SUBMIT_FEEDBACK_TOOL_NAME,
Expand Down Expand Up @@ -593,15 +595,13 @@ class TestFetchMcpToolsInternal:

def test_fetch_mcp_tools_single_page(self):
"""Test fetching tools with single page response."""
# Create mock tool response
mock_tool = MagicMock()
mock_tool.name = "test_tool"
mock_tool.description = "Test description"
mock_tool.inputSchema = {"type": "object", "properties": {"id": {"type": "string"}}}

mock_result = MagicMock()
mock_result.tools = [mock_tool]
mock_result.nextCursor = None
# Plain objects, not MagicMocks, which would answer any field name either mcp generation reads.
mock_tool = SimpleNamespace(
name="test_tool",
description="Test description",
inputSchema={"type": "object", "properties": {"id": {"type": "string"}}},
)
mock_result = SimpleNamespace(tools=[mock_tool], nextCursor=None)

# Create mock session
mock_session = AsyncMock()
Expand All @@ -611,7 +611,7 @@ def test_fetch_mcp_tools_single_page(self):
mock_session.__aexit__ = AsyncMock(return_value=None)

# Create mock streamable client
seen_clients: list[httpx.AsyncClient] = []
seen_clients: list[_mcp_http.AsyncClient] = []

@asynccontextmanager
async def mock_streamable_client(endpoint, *, http_client, **_kwargs: object):
Expand All @@ -634,7 +634,7 @@ async def mock_streamable_client(endpoint, *, http_client, **_kwargs: object):
# The caller's headers and timeout reach the HTTP client, on every leg.
[client] = seen_clients
assert client.headers["Authorization"] == "Basic test"
assert client.timeout == httpx.Timeout(7)
assert client.timeout == _mcp_http.Timeout(7)
assert client.follow_redirects is True

assert len(result) == 1
Expand All @@ -643,26 +643,15 @@ async def mock_streamable_client(endpoint, *, http_client, **_kwargs: object):
assert result[0].input_schema == {"type": "object", "properties": {"id": {"type": "string"}}}

def test_fetch_mcp_tools_with_pagination(self):
"""Test fetching tools with multiple pages."""
# First page
mock_tool1 = MagicMock()
mock_tool1.name = "tool_1"
mock_tool1.description = "Tool 1"
mock_tool1.inputSchema = {}

mock_result1 = MagicMock()
mock_result1.tools = [mock_tool1]
mock_result1.nextCursor = "cursor_page_2"

# Second page
mock_tool2 = MagicMock()
mock_tool2.name = "tool_2"
mock_tool2.description = "Tool 2"
mock_tool2.inputSchema = None # Test None inputSchema

mock_result2 = MagicMock()
mock_result2.tools = [mock_tool2]
mock_result2.nextCursor = None
"""Test fetching tools with multiple pages, as the installed mcp's own models carry them."""
schema = {"type": "object", "properties": {"id": {"type": "string"}}}
mock_result1 = mcp_types.ListToolsResult(
tools=[mcp_types.Tool(name="tool_1", description="Tool 1", inputSchema=schema)],
nextCursor="cursor_page_2",
)
mock_result2 = mcp_types.ListToolsResult(
tools=[mcp_types.Tool(name="tool_2", description="Tool 2", inputSchema={"type": "object"})]
)

# Create mock session with pagination
mock_session = AsyncMock()
Expand All @@ -688,8 +677,11 @@ async def mock_streamable_client(endpoint, **_kwargs: object):
assert len(result) == 2
assert result[0].name == "tool_1"
assert result[1].name == "tool_2"
assert result[1].input_schema == {} # None should become empty dict
assert mock_session.list_tools.call_count == 2
assert result[0].input_schema == schema
assert result[1].input_schema == {"type": "object"}
first_call, second_call = mock_session.list_tools.call_args_list
assert first_call.kwargs == {"params": None}
assert second_call.kwargs["params"].cursor == "cursor_page_2"


class TestCatalogCache:
Expand Down Expand Up @@ -1218,13 +1210,11 @@ class TestListingFailuresAreDiagnosable:
"""A failure must name the status, not hide it behind TaskGroup boilerplate."""

def test_http_error_carries_status_and_is_not_taskgroup_noise(self, monkeypatch):
import httpx

from stackone_ai.tools import _describe_mcp_failure

request = httpx.Request("POST", "https://api.example.com/mcp")
response = httpx.Response(412, text='{"message":"re-link the account"}', request=request)
inner = httpx.HTTPStatusError("412", request=request, response=response)
request = _mcp_http.Request("POST", "https://api.example.com/mcp")
response = _mcp_http.Response(412, text='{"message":"re-link the account"}', request=request)
inner = _mcp_http.HTTPStatusError("412", request=request, response=response)
# Mirrors reality: the MCP client raises inside a TaskGroup, so the real
# error arrives wrapped in an ExceptionGroup.
grouped = ExceptionGroup("unhandled errors in a TaskGroup", [inner])
Expand Down
Loading
Loading