mcp-intent 0.1.0__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.
- mcp_intent/__init__.py +34 -0
- mcp_intent/adapters/__init__.py +1 -0
- mcp_intent/adapters/fastmcp.py +111 -0
- mcp_intent/adapters/mcpserver.py +64 -0
- mcp_intent/anthropic_router.py +47 -0
- mcp_intent/cloud.py +304 -0
- mcp_intent/core.py +216 -0
- mcp_intent/entry.py +61 -0
- mcp_intent/guidance.py +115 -0
- mcp_intent/options.py +40 -0
- mcp_intent/py.typed +0 -0
- mcp_intent/routers.py +108 -0
- mcp_intent/sessions.py +110 -0
- mcp_intent-0.1.0.dist-info/METADATA +209 -0
- mcp_intent-0.1.0.dist-info/RECORD +18 -0
- mcp_intent-0.1.0.dist-info/WHEEL +4 -0
- mcp_intent-0.1.0.dist-info/licenses/LICENSE +202 -0
- mcp_intent-0.1.0.dist-info/licenses/NOTICE +4 -0
mcp_intent/__init__.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
"""Intent-first entry tool for MCP servers.
|
|
2
|
+
|
|
3
|
+
from fastmcp import FastMCP # or: from mcp.server.mcpserver import MCPServer
|
|
4
|
+
from mcp_intent import Guidance, add_entry_tool
|
|
5
|
+
|
|
6
|
+
mcp = FastMCP("my-server")
|
|
7
|
+
add_entry_tool(mcp, Guidance.from_yaml("guidance.yaml"))
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from .cloud import CloudRouter, CloudSink
|
|
11
|
+
from .core import EntryTool, IntentEvent
|
|
12
|
+
from .entry import add_entry_tool, entry_instructions
|
|
13
|
+
from .guidance import Family, Guidance, GuidanceError, Rule
|
|
14
|
+
from .options import EntryOptions
|
|
15
|
+
from .routers import KeywordRouter, Router
|
|
16
|
+
|
|
17
|
+
__version__ = "0.1.0"
|
|
18
|
+
|
|
19
|
+
__all__ = [
|
|
20
|
+
"CloudRouter",
|
|
21
|
+
"CloudSink",
|
|
22
|
+
"EntryOptions",
|
|
23
|
+
"EntryTool",
|
|
24
|
+
"Family",
|
|
25
|
+
"Guidance",
|
|
26
|
+
"GuidanceError",
|
|
27
|
+
"IntentEvent",
|
|
28
|
+
"KeywordRouter",
|
|
29
|
+
"Router",
|
|
30
|
+
"Rule",
|
|
31
|
+
"__version__",
|
|
32
|
+
"add_entry_tool",
|
|
33
|
+
"entry_instructions",
|
|
34
|
+
]
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Framework adapters: each registers the entry tool on one kind of MCP server."""
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
"""Adapter for FastMCP 4 (`pip install "mcp-intent[fastmcp]"`)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import contextvars
|
|
6
|
+
import time
|
|
7
|
+
from collections.abc import Sequence
|
|
8
|
+
from typing import Any, Unpack
|
|
9
|
+
|
|
10
|
+
import mcp.types as mt
|
|
11
|
+
from fastmcp import FastMCP
|
|
12
|
+
from fastmcp.server.dependencies import get_context, get_http_headers, get_http_request
|
|
13
|
+
from fastmcp.server.middleware import CallNext, Middleware, MiddlewareContext
|
|
14
|
+
from fastmcp.tools.base import Tool, ToolResult
|
|
15
|
+
|
|
16
|
+
from ..core import TOOL_ANNOTATIONS, TOOL_DESCRIPTION, EntryTool, describe_client, with_pointer
|
|
17
|
+
from ..guidance import Guidance
|
|
18
|
+
from ..options import EntryOptions
|
|
19
|
+
from ..sessions import EMPTY, Signals, signals_from
|
|
20
|
+
|
|
21
|
+
# The signals of the tool call being handled, set by the middleware and read by start_task.
|
|
22
|
+
_current: contextvars.ContextVar[Signals] = contextvars.ContextVar(
|
|
23
|
+
"mcp_intent_signals", default=EMPTY
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def add_entry_tool(
|
|
28
|
+
mcp: FastMCP,
|
|
29
|
+
guidance: Guidance,
|
|
30
|
+
*,
|
|
31
|
+
point_instructions: bool = True,
|
|
32
|
+
**options: Unpack[EntryOptions],
|
|
33
|
+
) -> EntryTool:
|
|
34
|
+
"""Register the entry tool on a FastMCP server. Options are described on
|
|
35
|
+
`mcp_intent.add_entry_tool`."""
|
|
36
|
+
entry = EntryTool(guidance, server_name=mcp.name, **options)
|
|
37
|
+
if point_instructions:
|
|
38
|
+
mcp.instructions = with_pointer(mcp.instructions, entry.tool_name)
|
|
39
|
+
|
|
40
|
+
async def start_task(task: str) -> dict[str, str]:
|
|
41
|
+
return await entry.call(task, _caller(), _current.get())
|
|
42
|
+
|
|
43
|
+
mcp.tool(
|
|
44
|
+
start_task,
|
|
45
|
+
name=entry.tool_name,
|
|
46
|
+
description=TOOL_DESCRIPTION,
|
|
47
|
+
meta=entry.meta,
|
|
48
|
+
annotations=dict(TOOL_ANNOTATIONS),
|
|
49
|
+
)
|
|
50
|
+
if entry.salt is not None:
|
|
51
|
+
mcp.add_middleware(_SessionMiddleware(entry))
|
|
52
|
+
return entry
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class _SessionMiddleware(Middleware):
|
|
56
|
+
"""Hashes the session signals of every tool call and records the call for coverage."""
|
|
57
|
+
|
|
58
|
+
def __init__(self, entry: EntryTool) -> None:
|
|
59
|
+
self._entry = entry
|
|
60
|
+
|
|
61
|
+
async def on_call_tool(
|
|
62
|
+
self,
|
|
63
|
+
context: MiddlewareContext[mt.CallToolRequestParams],
|
|
64
|
+
call_next: CallNext[mt.CallToolRequestParams, ToolResult],
|
|
65
|
+
) -> ToolResult:
|
|
66
|
+
salt = self._entry.salt
|
|
67
|
+
signals = signals_from(salt, get_http_headers(include_all=True),
|
|
68
|
+
getattr(context.message, "meta", None), _client_host()) if salt else EMPTY # fmt: skip
|
|
69
|
+
token = _current.set(signals)
|
|
70
|
+
started = time.monotonic()
|
|
71
|
+
failed = True
|
|
72
|
+
try:
|
|
73
|
+
result = await call_next(context)
|
|
74
|
+
failed = bool(getattr(result, "is_error", False) or getattr(result, "isError", False))
|
|
75
|
+
return result
|
|
76
|
+
finally:
|
|
77
|
+
_current.reset(token)
|
|
78
|
+
latency_ms = int((time.monotonic() - started) * 1000)
|
|
79
|
+
await self._entry.record_call(
|
|
80
|
+
context.message.name, latency_ms, failed, _caller(), signals
|
|
81
|
+
)
|
|
82
|
+
|
|
83
|
+
async def on_list_tools(
|
|
84
|
+
self,
|
|
85
|
+
context: MiddlewareContext[mt.ListToolsRequest],
|
|
86
|
+
call_next: CallNext[mt.ListToolsRequest, Sequence[Tool]],
|
|
87
|
+
) -> Sequence[Tool]:
|
|
88
|
+
tools = await call_next(context)
|
|
89
|
+
salt = self._entry.salt
|
|
90
|
+
if salt:
|
|
91
|
+
signals = signals_from(salt, get_http_headers(include_all=True), None, _client_host())
|
|
92
|
+
await self._entry.record_list(_caller(), signals)
|
|
93
|
+
return tools
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def _client_host() -> str | None:
|
|
97
|
+
try:
|
|
98
|
+
request = get_http_request()
|
|
99
|
+
except RuntimeError:
|
|
100
|
+
return None
|
|
101
|
+
return request.client.host if request.client else None
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _caller() -> str | None:
|
|
105
|
+
try:
|
|
106
|
+
params: Any = get_context().session.client_params
|
|
107
|
+
except RuntimeError:
|
|
108
|
+
params = None
|
|
109
|
+
info = getattr(params, "client_info", None) or getattr(params, "clientInfo", None)
|
|
110
|
+
agent = get_http_headers().get("user-agent")
|
|
111
|
+
return describe_client(getattr(info, "name", None), getattr(info, "version", None), agent)
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
"""Adapter for the official MCP Python SDK 2 (`MCPServer`; `pip install "mcp-intent[mcp]"`)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any, Unpack
|
|
6
|
+
|
|
7
|
+
from mcp.server.mcpserver import Context, MCPServer
|
|
8
|
+
from mcp_types import ToolAnnotations
|
|
9
|
+
|
|
10
|
+
from ..core import TOOL_DESCRIPTION, EntryTool, describe_client, with_pointer
|
|
11
|
+
from ..guidance import Guidance
|
|
12
|
+
from ..options import EntryOptions
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def add_entry_tool(
|
|
16
|
+
mcp: MCPServer[Any],
|
|
17
|
+
guidance: Guidance,
|
|
18
|
+
*,
|
|
19
|
+
point_instructions: bool = True,
|
|
20
|
+
**options: Unpack[EntryOptions],
|
|
21
|
+
) -> EntryTool:
|
|
22
|
+
"""Register the entry tool on an `MCPServer`. Options are described on
|
|
23
|
+
`mcp_intent.add_entry_tool`."""
|
|
24
|
+
entry = EntryTool(guidance, server_name=mcp.name, **options)
|
|
25
|
+
if point_instructions:
|
|
26
|
+
_point_instructions(mcp, entry.tool_name)
|
|
27
|
+
|
|
28
|
+
async def start_task(task: str, ctx: Context) -> dict[str, str]:
|
|
29
|
+
return await entry.call(task, _caller(ctx))
|
|
30
|
+
|
|
31
|
+
mcp.add_tool(
|
|
32
|
+
start_task,
|
|
33
|
+
name=entry.tool_name,
|
|
34
|
+
description=TOOL_DESCRIPTION,
|
|
35
|
+
annotations=ToolAnnotations(read_only_hint=True, open_world_hint=False),
|
|
36
|
+
meta=entry.meta,
|
|
37
|
+
structured_output=True,
|
|
38
|
+
)
|
|
39
|
+
return entry
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _point_instructions(mcp: MCPServer[Any], tool_name: str) -> None:
|
|
43
|
+
"""MCPServer takes instructions only at construction, so check them and refuse to start
|
|
44
|
+
without the pointer: a silent gap here costs the entry tool most of its first-call rate."""
|
|
45
|
+
if with_pointer(mcp.instructions, tool_name) != mcp.instructions:
|
|
46
|
+
raise ValueError(
|
|
47
|
+
"MCPServer takes its instructions only at construction. Build it with "
|
|
48
|
+
f"instructions=entry_instructions(..., tool_name={tool_name!r}) so agents are pointed "
|
|
49
|
+
"at the entry tool first, or pass point_instructions=False to add_entry_tool."
|
|
50
|
+
)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _caller(ctx: Context) -> str | None:
|
|
54
|
+
try:
|
|
55
|
+
params = ctx.request_context.session.client_params
|
|
56
|
+
except (AttributeError, ValueError): # no request in flight (direct calls in tests)
|
|
57
|
+
params = None
|
|
58
|
+
info = getattr(params, "client_info", None)
|
|
59
|
+
try:
|
|
60
|
+
headers = ctx.headers or {}
|
|
61
|
+
except (AttributeError, ValueError):
|
|
62
|
+
headers = {}
|
|
63
|
+
agent = headers.get("user-agent")
|
|
64
|
+
return describe_client(getattr(info, "name", None), getattr(info, "version", None), agent)
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
"""A router that asks a small Claude model to pick the family. Install `mcp-intent[anthropic]`.
|
|
2
|
+
|
|
3
|
+
This is the router used in the entry-tool benchmark (36 of 36 prompts routed correctly). Thinking is
|
|
4
|
+
turned off and the answer is capped at a few tokens, so a pick takes about half a second and a
|
|
5
|
+
few hundred input tokens.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from anthropic import AsyncAnthropic
|
|
11
|
+
|
|
12
|
+
from .guidance import Guidance
|
|
13
|
+
from .routers import MAX_FAMILIES, parse_families
|
|
14
|
+
|
|
15
|
+
DEFAULT_MODEL = "claude-haiku-5-5"
|
|
16
|
+
MAX_ANSWER_TOKENS = 30 # room for up to three family names
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def routing_prompt(options: str, task: str) -> str:
|
|
20
|
+
"""The prompt the Claude router and the Cloud use; checked on 470 single-goal and 54 two-goal
|
|
21
|
+
stated tasks from the benchmark (92% single tasks to exactly the right family, 96% two-goal
|
|
22
|
+
runs to both families)."""
|
|
23
|
+
return (
|
|
24
|
+
"Classify the task into the families it needs. Most tasks need exactly one family. Name "
|
|
25
|
+
"more than one only when the task asks for two or more separate things that belong to "
|
|
26
|
+
"different families (for example 'do X, then do Y'); a family's own sub-steps never count "
|
|
27
|
+
f"as separate things. Answer with the family names separated by commas, at most "
|
|
28
|
+
f"{MAX_FAMILIES}, in the order the task asks for them, or 'none' if no family fits."
|
|
29
|
+
f"\n\nFamilies:\n{options}\n\nTask: {task}"
|
|
30
|
+
)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class AnthropicRouter:
|
|
34
|
+
def __init__(self, client: AsyncAnthropic | None = None, model: str = DEFAULT_MODEL) -> None:
|
|
35
|
+
self._client = client or AsyncAnthropic(max_retries=0)
|
|
36
|
+
self._model = model
|
|
37
|
+
|
|
38
|
+
async def route(self, task: str, guidance: Guidance) -> list[str]:
|
|
39
|
+
options = "\n".join(f"- {name}: {f.when}" for name, f in guidance.families.items())
|
|
40
|
+
response = await self._client.messages.create(
|
|
41
|
+
model=self._model,
|
|
42
|
+
max_tokens=MAX_ANSWER_TOKENS,
|
|
43
|
+
thinking={"type": "disabled"},
|
|
44
|
+
messages=[{"role": "user", "content": routing_prompt(options, task)}],
|
|
45
|
+
)
|
|
46
|
+
text = "".join(b.text for b in response.content if b.type == "text")
|
|
47
|
+
return parse_families(text, guidance.families)
|
mcp_intent/cloud.py
ADDED
|
@@ -0,0 +1,304 @@
|
|
|
1
|
+
"""mcp-intent Cloud: send intent events to a hosted dashboard, and route tasks without a model key.
|
|
2
|
+
|
|
3
|
+
Both are opt-in. Nothing here runs unless the server owner passes a Cloud API key (or sets
|
|
4
|
+
`MCP_INTENT_API_KEY`). A Cloud failure is logged and never fails the agent's call.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import asyncio
|
|
10
|
+
import contextlib
|
|
11
|
+
import logging
|
|
12
|
+
import os
|
|
13
|
+
import time
|
|
14
|
+
from collections.abc import Mapping
|
|
15
|
+
from dataclasses import asdict
|
|
16
|
+
from datetime import UTC, datetime
|
|
17
|
+
from typing import TYPE_CHECKING, Any
|
|
18
|
+
|
|
19
|
+
import httpx2 as httpx
|
|
20
|
+
|
|
21
|
+
from .guidance import Guidance
|
|
22
|
+
from .routers import MAX_FAMILIES, KeywordRouter
|
|
23
|
+
|
|
24
|
+
if TYPE_CHECKING:
|
|
25
|
+
from .core import IntentEvent
|
|
26
|
+
|
|
27
|
+
log = logging.getLogger("mcp_intent.cloud")
|
|
28
|
+
|
|
29
|
+
API_KEY_ENV = "MCP_INTENT_API_KEY"
|
|
30
|
+
ENDPOINT_ENV = "MCP_INTENT_ENDPOINT"
|
|
31
|
+
DEFAULT_ENDPOINT = "https://app.mcp-intent.com"
|
|
32
|
+
FLUSH_INTERVAL_SECONDS = 2.0 # how long an event may wait before it is sent
|
|
33
|
+
MAX_BATCH = 200 # events per request; the Cloud accepts up to 500
|
|
34
|
+
MAX_QUEUE = 10_000 # events held while the Cloud is unreachable, then new ones are dropped
|
|
35
|
+
SEND_TIMEOUT_SECONDS = 5.0
|
|
36
|
+
ROUTE_TIMEOUT_SECONDS = 2.5 # inside the entry tool's own timeout (3 s by default)
|
|
37
|
+
ROUTE_CONNECT_SECONDS = 1.0 # an unreachable Cloud fails fast
|
|
38
|
+
CIRCUIT_OPEN_SECONDS = 60 # after the Cloud is unreachable or refuses, route locally this long
|
|
39
|
+
CIRCUIT_STATUSES = frozenset({401, 403, 429, 503}) # answers that will repeat; a 502 is one-off
|
|
40
|
+
RATE_LIMIT_PAUSE_SECONDS = 600 # after a daily-limit answer, hold events this long
|
|
41
|
+
PAUSE_CHECK_SECONDS = 30
|
|
42
|
+
MAX_TASK_CHARS = 1_000
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def resolve_key(api_key: str | None) -> str | None:
|
|
46
|
+
return api_key or os.environ.get(API_KEY_ENV) or None
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def resolve_endpoint(endpoint: str | None) -> str:
|
|
50
|
+
return (endpoint or os.environ.get(ENDPOINT_ENV) or DEFAULT_ENDPOINT).rstrip("/")
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class CloudSink:
|
|
54
|
+
"""Batches intent events and posts them to the Cloud in the background.
|
|
55
|
+
|
|
56
|
+
Use it as `on_intent`, or let `add_entry_tool(cloud_key=...)` wire it for you.
|
|
57
|
+
"""
|
|
58
|
+
|
|
59
|
+
def __init__(
|
|
60
|
+
self,
|
|
61
|
+
api_key: str | None = None,
|
|
62
|
+
*,
|
|
63
|
+
endpoint: str | None = None,
|
|
64
|
+
server_name: str | None = None,
|
|
65
|
+
send_task_text: bool = True,
|
|
66
|
+
transport: httpx.AsyncBaseTransport | None = None,
|
|
67
|
+
) -> None:
|
|
68
|
+
key = resolve_key(api_key)
|
|
69
|
+
if not key:
|
|
70
|
+
raise ValueError(f"CloudSink needs an API key: pass api_key or set {API_KEY_ENV}")
|
|
71
|
+
self._key = key
|
|
72
|
+
self._endpoint = resolve_endpoint(endpoint)
|
|
73
|
+
self.server_name = server_name
|
|
74
|
+
self._send_task_text = send_task_text
|
|
75
|
+
self._transport = transport
|
|
76
|
+
self._queue: list[dict[str, Any]] = []
|
|
77
|
+
# One worker per event loop: an asyncio.Event or client made on one loop cannot be used
|
|
78
|
+
# from another (servers and tests may run several loops over a process's life).
|
|
79
|
+
self._worker: asyncio.Task[None] | None = None
|
|
80
|
+
self._worker_loop: asyncio.AbstractEventLoop | None = None
|
|
81
|
+
self._wake: asyncio.Event | None = None
|
|
82
|
+
self._paused_until = 0.0
|
|
83
|
+
self._dropped = 0
|
|
84
|
+
# Family name -> tool names its steps mention; sent once so the Cloud can infer the
|
|
85
|
+
# family of sessions that never called the entry tool. Never steps or rules.
|
|
86
|
+
self.guidance_summary: dict[str, list[str]] | None = None
|
|
87
|
+
self._summary_sent = False
|
|
88
|
+
|
|
89
|
+
async def __call__(self, event: IntentEvent) -> None:
|
|
90
|
+
item = asdict(event)
|
|
91
|
+
item["ts"] = datetime.now(UTC).isoformat()
|
|
92
|
+
item["server"] = self.server_name
|
|
93
|
+
item["task"] = item["task"][:MAX_TASK_CHARS] if self._send_task_text else None
|
|
94
|
+
self._enqueue(item)
|
|
95
|
+
|
|
96
|
+
async def record_call(
|
|
97
|
+
self,
|
|
98
|
+
tool: str,
|
|
99
|
+
latency_ms: int,
|
|
100
|
+
error: bool,
|
|
101
|
+
client: str | None,
|
|
102
|
+
signals: Mapping[str, str | None],
|
|
103
|
+
) -> None:
|
|
104
|
+
"""Queue one tool-call record: name, timing, host and hashed session signals."""
|
|
105
|
+
self._enqueue({
|
|
106
|
+
"kind": "call", "ts": datetime.now(UTC).isoformat(), "tool": tool,
|
|
107
|
+
"latency_ms": latency_ms, "error": "error" if error else None, "client": client,
|
|
108
|
+
"server": self.server_name, **signals,
|
|
109
|
+
}) # fmt: skip
|
|
110
|
+
|
|
111
|
+
async def record_list(self, client: str | None, signals: Mapping[str, str | None]) -> None:
|
|
112
|
+
"""Queue a marker that the host listed tools: hosts do it when a conversation starts."""
|
|
113
|
+
self._enqueue({
|
|
114
|
+
"kind": "list", "ts": datetime.now(UTC).isoformat(), "client": client,
|
|
115
|
+
"server": self.server_name, **signals,
|
|
116
|
+
}) # fmt: skip
|
|
117
|
+
|
|
118
|
+
def _enqueue(self, item: dict[str, Any]) -> None:
|
|
119
|
+
if len(self._queue) >= MAX_QUEUE:
|
|
120
|
+
self._dropped += 1
|
|
121
|
+
if self._dropped == 1 or self._dropped % 1000 == 0:
|
|
122
|
+
log.error("mcp-intent cloud queue full; %d events dropped so far", self._dropped)
|
|
123
|
+
return
|
|
124
|
+
self._queue.append(item)
|
|
125
|
+
self._ensure_worker()
|
|
126
|
+
if len(self._queue) >= MAX_BATCH and self._wake is not None:
|
|
127
|
+
self._wake.set()
|
|
128
|
+
|
|
129
|
+
def _ensure_worker(self) -> None:
|
|
130
|
+
loop = asyncio.get_running_loop()
|
|
131
|
+
alive = (
|
|
132
|
+
self._worker is not None
|
|
133
|
+
and not self._worker.done()
|
|
134
|
+
and self._worker_loop is loop
|
|
135
|
+
and not loop.is_closed()
|
|
136
|
+
)
|
|
137
|
+
if not alive:
|
|
138
|
+
self._wake = asyncio.Event()
|
|
139
|
+
self._worker_loop = loop
|
|
140
|
+
self._worker = loop.create_task(self._run())
|
|
141
|
+
|
|
142
|
+
async def _run(self) -> None:
|
|
143
|
+
wake = self._wake
|
|
144
|
+
if wake is None:
|
|
145
|
+
return
|
|
146
|
+
async with httpx.AsyncClient(
|
|
147
|
+
base_url=self._endpoint,
|
|
148
|
+
timeout=SEND_TIMEOUT_SECONDS,
|
|
149
|
+
transport=self._transport,
|
|
150
|
+
headers={"Authorization": f"Bearer {self._key}"},
|
|
151
|
+
) as client:
|
|
152
|
+
while self._queue:
|
|
153
|
+
try:
|
|
154
|
+
await asyncio.wait_for(wake.wait(), FLUSH_INTERVAL_SECONDS)
|
|
155
|
+
except TimeoutError:
|
|
156
|
+
pass
|
|
157
|
+
wake.clear()
|
|
158
|
+
pause = self._paused_until - time.monotonic()
|
|
159
|
+
if pause > 0:
|
|
160
|
+
await asyncio.sleep(min(pause, PAUSE_CHECK_SECONDS))
|
|
161
|
+
continue
|
|
162
|
+
await self._send(client)
|
|
163
|
+
# Normal exit only: events queued while the client was closing would otherwise wait for
|
|
164
|
+
# the next call. Not in a `finally`, so cancellation at shutdown and finalisation of an
|
|
165
|
+
# abandoned task (no running loop) never start a new worker.
|
|
166
|
+
if self._queue and asyncio.current_task() is self._worker:
|
|
167
|
+
self._worker = None
|
|
168
|
+
self._ensure_worker()
|
|
169
|
+
|
|
170
|
+
async def _send(self, client: httpx.AsyncClient, *, retry_pause: bool = True) -> None:
|
|
171
|
+
batch, self._queue = self._queue[:MAX_BATCH], self._queue[MAX_BATCH:]
|
|
172
|
+
try:
|
|
173
|
+
body: dict[str, Any] = {"events": batch}
|
|
174
|
+
if self.guidance_summary is not None and not self._summary_sent:
|
|
175
|
+
body["guidance"] = self.guidance_summary
|
|
176
|
+
response = await client.post("/v1/events", json=body)
|
|
177
|
+
except httpx.HTTPError as exc:
|
|
178
|
+
log.error("mcp-intent cloud unreachable, %d events kept for retry: %s", len(batch), exc)
|
|
179
|
+
self._queue = batch + self._queue
|
|
180
|
+
if retry_pause:
|
|
181
|
+
await asyncio.sleep(FLUSH_INTERVAL_SECONDS)
|
|
182
|
+
return
|
|
183
|
+
except BaseException:
|
|
184
|
+
self._queue = batch + self._queue # cancelled at shutdown: keep the batch
|
|
185
|
+
raise
|
|
186
|
+
if response.status_code == 429:
|
|
187
|
+
self._paused_until = time.monotonic() + RATE_LIMIT_PAUSE_SECONDS
|
|
188
|
+
log.error("mcp-intent cloud daily limit reached; %d events held, retrying in %d min",
|
|
189
|
+
len(batch), RATE_LIMIT_PAUSE_SECONDS // 60) # fmt: skip
|
|
190
|
+
self._queue = batch + self._queue
|
|
191
|
+
elif response.status_code >= 500:
|
|
192
|
+
log.error("mcp-intent cloud answered %s, %d events kept for retry",
|
|
193
|
+
response.status_code, len(batch)) # fmt: skip
|
|
194
|
+
self._queue = batch + self._queue
|
|
195
|
+
if retry_pause:
|
|
196
|
+
await asyncio.sleep(FLUSH_INTERVAL_SECONDS)
|
|
197
|
+
elif response.status_code >= 400:
|
|
198
|
+
# A 4xx will not succeed on retry (bad key, malformed batch): drop it loudly.
|
|
199
|
+
log.error("mcp-intent cloud rejected %d events with %s: %s",
|
|
200
|
+
len(batch), response.status_code, response.text[:200]) # fmt: skip
|
|
201
|
+
else:
|
|
202
|
+
self._summary_sent = True
|
|
203
|
+
|
|
204
|
+
async def flush(self) -> None:
|
|
205
|
+
"""Send what is queued now, stopping at the first batch kept for retry (for tests and
|
|
206
|
+
clean shutdowns; it never waits out an outage or a daily-limit pause)."""
|
|
207
|
+
async with httpx.AsyncClient(
|
|
208
|
+
base_url=self._endpoint,
|
|
209
|
+
timeout=SEND_TIMEOUT_SECONDS,
|
|
210
|
+
transport=self._transport,
|
|
211
|
+
headers={"Authorization": f"Bearer {self._key}"},
|
|
212
|
+
) as client:
|
|
213
|
+
while self._queue and time.monotonic() >= self._paused_until:
|
|
214
|
+
before = len(self._queue)
|
|
215
|
+
await self._send(client, retry_pause=False)
|
|
216
|
+
if len(self._queue) >= before:
|
|
217
|
+
return
|
|
218
|
+
# Queue empty: let the background worker see it and finish, so none outlives the loop.
|
|
219
|
+
worker = self._worker
|
|
220
|
+
if worker is not None and self._worker_loop is asyncio.get_running_loop():
|
|
221
|
+
if self._wake is not None:
|
|
222
|
+
self._wake.set()
|
|
223
|
+
await worker
|
|
224
|
+
|
|
225
|
+
async def aclose(self) -> None:
|
|
226
|
+
"""Flush, then stop the background worker. Call it when the server shuts down; events
|
|
227
|
+
still held (Cloud down or over its daily limit) are logged as dropped."""
|
|
228
|
+
await self.flush()
|
|
229
|
+
worker, self._worker = self._worker, None
|
|
230
|
+
if worker is not None and not worker.done():
|
|
231
|
+
worker.cancel()
|
|
232
|
+
if self._worker_loop is asyncio.get_running_loop():
|
|
233
|
+
with contextlib.suppress(asyncio.CancelledError):
|
|
234
|
+
await worker
|
|
235
|
+
if self._queue:
|
|
236
|
+
log.error("mcp-intent cloud closed with %d events unsent", len(self._queue))
|
|
237
|
+
self._queue = []
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
class CloudRouter:
|
|
241
|
+
"""Routes the stated task on the Cloud, so the server needs no model key of its own.
|
|
242
|
+
|
|
243
|
+
Sends the task and the families' names, descriptions and keywords; the steps and rules stay
|
|
244
|
+
on the server. When the Cloud fails, the keyword router answers instead, and the Cloud is
|
|
245
|
+
skipped for a minute so a Cloud outage does not add a timeout to every call.
|
|
246
|
+
"""
|
|
247
|
+
|
|
248
|
+
def __init__(
|
|
249
|
+
self,
|
|
250
|
+
api_key: str | None = None,
|
|
251
|
+
*,
|
|
252
|
+
endpoint: str | None = None,
|
|
253
|
+
transport: httpx.AsyncBaseTransport | None = None,
|
|
254
|
+
) -> None:
|
|
255
|
+
key = resolve_key(api_key)
|
|
256
|
+
if not key:
|
|
257
|
+
raise ValueError(f"CloudRouter needs an API key: pass api_key or set {API_KEY_ENV}")
|
|
258
|
+
self._key = key
|
|
259
|
+
self._endpoint = resolve_endpoint(endpoint)
|
|
260
|
+
self._transport = transport
|
|
261
|
+
self._fallback = KeywordRouter()
|
|
262
|
+
self._skip_until = 0.0
|
|
263
|
+
|
|
264
|
+
async def route(self, task: str, guidance: Guidance) -> str | list[str] | None:
|
|
265
|
+
if time.monotonic() < self._skip_until:
|
|
266
|
+
return await self._fallback.route(task, guidance)
|
|
267
|
+
families = [
|
|
268
|
+
{"name": f.name, "when": f.when, "keywords": list(f.keywords)}
|
|
269
|
+
for f in guidance.families.values()
|
|
270
|
+
]
|
|
271
|
+
try:
|
|
272
|
+
# A client per call: routing happens once per agent session, and a pooled client
|
|
273
|
+
# would be tied to the event loop that created it.
|
|
274
|
+
async with httpx.AsyncClient(
|
|
275
|
+
base_url=self._endpoint,
|
|
276
|
+
timeout=httpx.Timeout(ROUTE_TIMEOUT_SECONDS, connect=ROUTE_CONNECT_SECONDS),
|
|
277
|
+
transport=self._transport,
|
|
278
|
+
headers={"Authorization": f"Bearer {self._key}"},
|
|
279
|
+
) as client:
|
|
280
|
+
response = await client.post(
|
|
281
|
+
"/v1/route", json={"task": task[:MAX_TASK_CHARS], "families": families}
|
|
282
|
+
)
|
|
283
|
+
response.raise_for_status()
|
|
284
|
+
except httpx.HTTPError as exc:
|
|
285
|
+
status = exc.response.status_code if isinstance(exc, httpx.HTTPStatusError) else None
|
|
286
|
+
if status is None or status in CIRCUIT_STATUSES:
|
|
287
|
+
# Unreachable, over its limit or not configured: stop asking for a while.
|
|
288
|
+
self._skip_until = time.monotonic() + CIRCUIT_OPEN_SECONDS
|
|
289
|
+
log.error("mcp-intent cloud routing failed (%s), keyword routing answered: %s",
|
|
290
|
+
status or "network", exc) # fmt: skip
|
|
291
|
+
return await self._fallback.route(task, guidance)
|
|
292
|
+
try:
|
|
293
|
+
body = response.json()
|
|
294
|
+
except ValueError as exc: # a 200 that is not JSON: answer locally, as for any failure
|
|
295
|
+
log.error("mcp-intent cloud routing answer unreadable, keyword routing answered: %s",
|
|
296
|
+
exc) # fmt: skip
|
|
297
|
+
return await self._fallback.route(task, guidance)
|
|
298
|
+
if not isinstance(body, dict):
|
|
299
|
+
return None
|
|
300
|
+
names = body.get("families")
|
|
301
|
+
if not isinstance(names, list): # a Cloud from before multi-family routing
|
|
302
|
+
names = [body["family"]] if isinstance(body.get("family"), str) else []
|
|
303
|
+
known = [n for n in names if isinstance(n, str) and n in guidance.families]
|
|
304
|
+
return list(dict.fromkeys(known))[:MAX_FAMILIES]
|