foundgine 3.4.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.
- foundgine/__init__.py +56 -0
- foundgine/_http.py +50 -0
- foundgine/client.py +145 -0
- foundgine/errors.py +60 -0
- foundgine/http.py +87 -0
- foundgine/mcp.py +306 -0
- foundgine/py.typed +0 -0
- foundgine/sse.py +103 -0
- foundgine/sync.py +172 -0
- foundgine/types.py +48 -0
- foundgine/workflows.py +428 -0
- foundgine-3.4.0.dist-info/METADATA +131 -0
- foundgine-3.4.0.dist-info/RECORD +15 -0
- foundgine-3.4.0.dist-info/WHEEL +4 -0
- foundgine-3.4.0.dist-info/licenses/LICENSE +181 -0
foundgine/__init__.py
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
"""Python SDK for Foundgine (transport only). API aligned with @foundgine/typescript."""
|
|
2
|
+
|
|
3
|
+
from .client import DEFAULT_TIMEOUT, FoundgineClient, Tool, ToolResult
|
|
4
|
+
from .errors import (
|
|
5
|
+
FoundgineAbortError,
|
|
6
|
+
FoundgineError,
|
|
7
|
+
FoundgineHttpError,
|
|
8
|
+
FoundgineResyncRequiredError,
|
|
9
|
+
FoundgineRpcError,
|
|
10
|
+
FoundgineSessionExpiredError,
|
|
11
|
+
FoundgineWatchTimeoutError,
|
|
12
|
+
)
|
|
13
|
+
from .http import TokenProvider
|
|
14
|
+
from .mcp import DEFAULT_PROTOCOL_VERSION, McpSession
|
|
15
|
+
from .sse import SseEvent, SseParser
|
|
16
|
+
from .sync import FoundgineSyncClient, SyncWorkflowClient
|
|
17
|
+
from .workflows import (
|
|
18
|
+
StartAndWatch,
|
|
19
|
+
WorkflowClient,
|
|
20
|
+
WorkflowProcessDescription,
|
|
21
|
+
WorkflowStartResult,
|
|
22
|
+
WorkflowStatus,
|
|
23
|
+
WorkflowStepDescription,
|
|
24
|
+
WorkflowWatch,
|
|
25
|
+
)
|
|
26
|
+
|
|
27
|
+
__version__ = "3.4.0"
|
|
28
|
+
|
|
29
|
+
__all__ = [
|
|
30
|
+
"DEFAULT_PROTOCOL_VERSION",
|
|
31
|
+
"DEFAULT_TIMEOUT",
|
|
32
|
+
"FoundgineAbortError",
|
|
33
|
+
"FoundgineClient",
|
|
34
|
+
"FoundgineError",
|
|
35
|
+
"FoundgineHttpError",
|
|
36
|
+
"FoundgineResyncRequiredError",
|
|
37
|
+
"FoundgineRpcError",
|
|
38
|
+
"FoundgineSessionExpiredError",
|
|
39
|
+
"FoundgineSyncClient",
|
|
40
|
+
"FoundgineWatchTimeoutError",
|
|
41
|
+
"McpSession",
|
|
42
|
+
"SseEvent",
|
|
43
|
+
"SseParser",
|
|
44
|
+
"StartAndWatch",
|
|
45
|
+
"SyncWorkflowClient",
|
|
46
|
+
"TokenProvider",
|
|
47
|
+
"Tool",
|
|
48
|
+
"ToolResult",
|
|
49
|
+
"WorkflowClient",
|
|
50
|
+
"WorkflowProcessDescription",
|
|
51
|
+
"WorkflowStartResult",
|
|
52
|
+
"WorkflowStatus",
|
|
53
|
+
"WorkflowStepDescription",
|
|
54
|
+
"WorkflowWatch",
|
|
55
|
+
"__version__",
|
|
56
|
+
]
|
foundgine/_http.py
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
"""Private HTTP helpers shared by the MCP and workflow clients."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import inspect
|
|
6
|
+
import json
|
|
7
|
+
from collections.abc import Awaitable, Callable
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
import httpx
|
|
11
|
+
|
|
12
|
+
from .errors import FoundgineHttpError
|
|
13
|
+
|
|
14
|
+
TokenProvider = str | Callable[[], str | Awaitable[str | None] | None] | None
|
|
15
|
+
DEFAULT_TIMEOUT = httpx.Timeout(connect=10.0, read=60.0, write=60.0, pool=10.0)
|
|
16
|
+
STREAM_TIMEOUT = httpx.Timeout(connect=10.0, read=None, write=60.0, pool=10.0)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
async def resolve_token(token: TokenProvider) -> str | None:
|
|
20
|
+
"""Resolve a fixed, synchronous, or asynchronous bearer-token provider."""
|
|
21
|
+
value: Any = token() if callable(token) else token
|
|
22
|
+
if inspect.isawaitable(value):
|
|
23
|
+
value = await value
|
|
24
|
+
return value if isinstance(value, str) and value else None
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def join_url(base_url: str, path: str) -> str:
|
|
28
|
+
"""Join a base URL and absolute-or-relative path without duplicate slashes."""
|
|
29
|
+
return base_url.rstrip("/") + "/" + path.lstrip("/")
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def error_for(status: int, body: bytes, secret: str | None = None) -> FoundgineHttpError:
|
|
33
|
+
"""Create a safe HTTP error; request headers and credentials are never included."""
|
|
34
|
+
parsed: Any = None
|
|
35
|
+
detail: str | None = None
|
|
36
|
+
try:
|
|
37
|
+
parsed = json.loads(body.decode("utf-8", errors="replace")) if body else None
|
|
38
|
+
except ValueError:
|
|
39
|
+
pass
|
|
40
|
+
if isinstance(parsed, dict):
|
|
41
|
+
value = parsed.get("error")
|
|
42
|
+
if isinstance(value, str):
|
|
43
|
+
detail = value
|
|
44
|
+
elif isinstance(value, dict) and isinstance(value.get("message"), str):
|
|
45
|
+
detail = value["message"]
|
|
46
|
+
if detail is None and body and parsed is None:
|
|
47
|
+
detail = body.decode("utf-8", errors="replace")[:200].strip() or None
|
|
48
|
+
if detail and secret:
|
|
49
|
+
detail = detail.replace(secret, "[redacted]")
|
|
50
|
+
return FoundgineHttpError(status, f"HTTP {status}: {detail}" if detail else f"HTTP {status}", parsed)
|
foundgine/client.py
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
"""High-level client. Mirrors ``client.ts``."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import re
|
|
7
|
+
from collections.abc import AsyncGenerator
|
|
8
|
+
from dataclasses import dataclass, field
|
|
9
|
+
from types import TracebackType
|
|
10
|
+
from typing import Any
|
|
11
|
+
|
|
12
|
+
import httpx
|
|
13
|
+
|
|
14
|
+
from .errors import FoundgineError
|
|
15
|
+
from .http import TokenProvider
|
|
16
|
+
from .mcp import DEFAULT_PROTOCOL_VERSION, McpSession
|
|
17
|
+
from .workflows import WorkflowClient
|
|
18
|
+
|
|
19
|
+
DEFAULT_TIMEOUT = httpx.Timeout(60.0, connect=10.0)
|
|
20
|
+
"""httpx's own 5 s default would break slow tool calls, so the SDK sets explicit timeouts."""
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@dataclass(frozen=True, slots=True)
|
|
24
|
+
class Tool:
|
|
25
|
+
"""One MCP tool description from ``tools/list``."""
|
|
26
|
+
|
|
27
|
+
name: str
|
|
28
|
+
description: str | None = None
|
|
29
|
+
input_schema: dict[str, Any] = field(default_factory=dict)
|
|
30
|
+
raw: dict[str, Any] = field(default_factory=dict)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@dataclass(frozen=True, slots=True)
|
|
34
|
+
class ToolResult:
|
|
35
|
+
"""Result of ``tools/call``. A failing tool is ``is_error=True`` data, not an exception."""
|
|
36
|
+
|
|
37
|
+
content: list[dict[str, Any]]
|
|
38
|
+
is_error: bool
|
|
39
|
+
structured_content: Any = None
|
|
40
|
+
raw: dict[str, Any] = field(default_factory=dict)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class FoundgineClient:
|
|
44
|
+
"""Thin client for Foundgine's MCP and workflow HTTP surfaces.
|
|
45
|
+
|
|
46
|
+
``token`` may be a string or a sync/async callable, resolved for every request. If ``http_client`` is
|
|
47
|
+
supplied the caller owns it and :meth:`close` leaves it open. Redirects are not followed.
|
|
48
|
+
"""
|
|
49
|
+
|
|
50
|
+
def __init__(
|
|
51
|
+
self,
|
|
52
|
+
base_url: str,
|
|
53
|
+
token: TokenProvider = None,
|
|
54
|
+
*,
|
|
55
|
+
http_client: httpx.AsyncClient | None = None,
|
|
56
|
+
mcp_path: str | None = None,
|
|
57
|
+
protocol_version: str | None = None,
|
|
58
|
+
timeout: httpx.Timeout | float | None = None,
|
|
59
|
+
) -> None:
|
|
60
|
+
if not re.match(r"^https?://", base_url, re.IGNORECASE):
|
|
61
|
+
raise ValueError("base_url must start with http:// or https://")
|
|
62
|
+
self.base_url = base_url.rstrip("/")
|
|
63
|
+
self._owns_http = http_client is None
|
|
64
|
+
self._http = http_client or httpx.AsyncClient(
|
|
65
|
+
timeout=DEFAULT_TIMEOUT if timeout is None else timeout, follow_redirects=False
|
|
66
|
+
)
|
|
67
|
+
self._closed = False
|
|
68
|
+
self.mcp = McpSession(
|
|
69
|
+
self.base_url,
|
|
70
|
+
self._http,
|
|
71
|
+
path=mcp_path or "/mcp",
|
|
72
|
+
protocol_version=protocol_version or DEFAULT_PROTOCOL_VERSION,
|
|
73
|
+
token=token,
|
|
74
|
+
)
|
|
75
|
+
self.workflows = WorkflowClient(self.base_url, self._http, token)
|
|
76
|
+
|
|
77
|
+
async def list_capabilities(self) -> list[Tool]:
|
|
78
|
+
"""List every tool, following ``nextCursor`` until exhausted."""
|
|
79
|
+
tools: list[Tool] = []
|
|
80
|
+
cursor: str | None = None
|
|
81
|
+
while True:
|
|
82
|
+
result = await self.mcp.request("tools/list", {"cursor": cursor} if cursor else {})
|
|
83
|
+
if not isinstance(result, dict):
|
|
84
|
+
raise FoundgineError("tools/list returned no result object")
|
|
85
|
+
items = result.get("tools")
|
|
86
|
+
if isinstance(items, list):
|
|
87
|
+
for item in items:
|
|
88
|
+
if not isinstance(item, dict) or not isinstance(item.get("name"), str):
|
|
89
|
+
continue
|
|
90
|
+
schema = item.get("inputSchema")
|
|
91
|
+
description = item.get("description")
|
|
92
|
+
tools.append(
|
|
93
|
+
Tool(
|
|
94
|
+
name=item["name"],
|
|
95
|
+
description=description if isinstance(description, str) else None,
|
|
96
|
+
input_schema=schema if isinstance(schema, dict) else {},
|
|
97
|
+
raw=item,
|
|
98
|
+
)
|
|
99
|
+
)
|
|
100
|
+
next_cursor = result.get("nextCursor")
|
|
101
|
+
cursor = next_cursor if isinstance(next_cursor, str) and next_cursor else None
|
|
102
|
+
if cursor is None:
|
|
103
|
+
return tools
|
|
104
|
+
|
|
105
|
+
async def execute(
|
|
106
|
+
self, name: str, arguments: dict[str, Any] | None = None, *, cancel: asyncio.Event | None = None
|
|
107
|
+
) -> ToolResult:
|
|
108
|
+
"""Call a tool. Protocol failures raise :class:`FoundgineRpcError`; tool failures set ``is_error``."""
|
|
109
|
+
result = await self.mcp.request("tools/call", {"name": name, "arguments": arguments or {}}, cancel=cancel)
|
|
110
|
+
if not isinstance(result, dict):
|
|
111
|
+
raise FoundgineError("tools/call returned no result object")
|
|
112
|
+
content = result.get("content")
|
|
113
|
+
return ToolResult(
|
|
114
|
+
content=[c for c in content if isinstance(c, dict)] if isinstance(content, list) else [],
|
|
115
|
+
is_error=result.get("isError") is True,
|
|
116
|
+
structured_content=result.get("structuredContent"),
|
|
117
|
+
raw=result,
|
|
118
|
+
)
|
|
119
|
+
|
|
120
|
+
def notifications(
|
|
121
|
+
self,
|
|
122
|
+
*,
|
|
123
|
+
cancel: asyncio.Event | None = None,
|
|
124
|
+
last_event_id: str | None = None,
|
|
125
|
+
reconnect_delay: float = 1.0,
|
|
126
|
+
) -> AsyncGenerator[dict[str, Any], None]:
|
|
127
|
+
"""Resumable notification stream. See :meth:`McpSession.notifications`."""
|
|
128
|
+
return self.mcp.notifications(cancel=cancel, last_event_id=last_event_id, reconnect_delay=reconnect_delay)
|
|
129
|
+
|
|
130
|
+
async def close(self) -> None:
|
|
131
|
+
"""End the MCP session and close the HTTP client if the SDK created it. Idempotent."""
|
|
132
|
+
if self._closed:
|
|
133
|
+
return
|
|
134
|
+
self._closed = True
|
|
135
|
+
await self.mcp.close()
|
|
136
|
+
if self._owns_http:
|
|
137
|
+
await self._http.aclose()
|
|
138
|
+
|
|
139
|
+
async def __aenter__(self) -> FoundgineClient:
|
|
140
|
+
return self
|
|
141
|
+
|
|
142
|
+
async def __aexit__(
|
|
143
|
+
self, exc_type: type[BaseException] | None, exc: BaseException | None, tb: TracebackType | None
|
|
144
|
+
) -> None:
|
|
145
|
+
await self.close()
|
foundgine/errors.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
"""Exception types. They mirror the TypeScript SDK's error classes (REQUIREMENTS.md, PY-ERR-1)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class FoundgineError(Exception):
|
|
9
|
+
"""Base class for every error this SDK raises on purpose."""
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class FoundgineHttpError(FoundgineError):
|
|
13
|
+
"""The server answered with an error status. ``status`` is the HTTP status code."""
|
|
14
|
+
|
|
15
|
+
def __init__(self, status: int, message: str | None = None, body: Any = None) -> None:
|
|
16
|
+
self.status = status
|
|
17
|
+
self.body = body
|
|
18
|
+
self.message = message or f"HTTP {status}"
|
|
19
|
+
super().__init__(self.message)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class FoundgineSessionExpiredError(FoundgineHttpError):
|
|
23
|
+
"""HTTP 404 on an MCP session call: the session is gone. The next call starts a new one."""
|
|
24
|
+
|
|
25
|
+
def __init__(self, message: str | None = None, body: Any = None) -> None:
|
|
26
|
+
super().__init__(404, message or "MCP session expired or unknown", body)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class FoundgineResyncRequiredError(FoundgineHttpError):
|
|
30
|
+
"""HTTP 410 on the notification stream: the requested event id is no longer buffered. Re-read state, then resume."""
|
|
31
|
+
|
|
32
|
+
def __init__(self, message: str | None = None, body: Any = None) -> None:
|
|
33
|
+
super().__init__(
|
|
34
|
+
410, message or "Event replay buffer no longer holds the requested event; resync required", body
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class FoundgineRpcError(FoundgineError):
|
|
39
|
+
"""A JSON-RPC ``error`` object (a protocol failure; a failing tool is data, not this)."""
|
|
40
|
+
|
|
41
|
+
def __init__(self, code: int, message: str, data: Any = None) -> None:
|
|
42
|
+
self.code = code
|
|
43
|
+
self.data = data
|
|
44
|
+
self.message = message
|
|
45
|
+
super().__init__(f"JSON-RPC error {code}: {message}")
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class FoundgineAbortError(FoundgineError):
|
|
49
|
+
"""The operation was stopped by the caller (cancel event or ``Watch.stop()``)."""
|
|
50
|
+
|
|
51
|
+
def __init__(self, message: str = "Operation aborted") -> None:
|
|
52
|
+
super().__init__(message)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class FoundgineWatchTimeoutError(FoundgineError):
|
|
56
|
+
"""``Watch.done`` ran out of time. ``last_status`` is the last status seen, or None."""
|
|
57
|
+
|
|
58
|
+
def __init__(self, last_status: Any = None, message: str = "Timed out waiting for the workflow to finish") -> None:
|
|
59
|
+
self.last_status = last_status
|
|
60
|
+
super().__init__(message)
|
foundgine/http.py
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
"""HTTP helpers shared by the MCP and workflow clients. Mirrors ``http.ts``."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import inspect
|
|
7
|
+
import json
|
|
8
|
+
from collections.abc import Awaitable, Callable
|
|
9
|
+
from typing import Any, TypeVar
|
|
10
|
+
|
|
11
|
+
import httpx
|
|
12
|
+
|
|
13
|
+
from .errors import FoundgineAbortError, FoundgineHttpError
|
|
14
|
+
|
|
15
|
+
T = TypeVar("T")
|
|
16
|
+
|
|
17
|
+
TokenProvider = str | Callable[[], "Awaitable[str | None] | str | None"] | None
|
|
18
|
+
"""A bearer token: a string, or a sync/async callable resolved for every request."""
|
|
19
|
+
|
|
20
|
+
USER_AGENT = "foundgine-python/3.4.0"
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
async def resolve_token(token: TokenProvider) -> str | None:
|
|
24
|
+
"""Resolve a token provider. Empty or non-string values mean "no token"."""
|
|
25
|
+
value: Any = token
|
|
26
|
+
if callable(value):
|
|
27
|
+
value = value()
|
|
28
|
+
if inspect.isawaitable(value):
|
|
29
|
+
value = await value
|
|
30
|
+
return value if isinstance(value, str) and value else None
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def join_url(base_url: str, path: str) -> str:
|
|
34
|
+
return f"{base_url.rstrip('/')}/{path.lstrip('/')}"
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
async def error_for(response: httpx.Response) -> FoundgineHttpError:
|
|
38
|
+
"""Build an HTTP error from a non-success response (reading the body if it is still streaming)."""
|
|
39
|
+
await response.aread()
|
|
40
|
+
text = response.text
|
|
41
|
+
body: Any = None
|
|
42
|
+
try:
|
|
43
|
+
body = json.loads(text) if text else None
|
|
44
|
+
except ValueError:
|
|
45
|
+
body = None
|
|
46
|
+
detail: str | None = None
|
|
47
|
+
if isinstance(body, dict):
|
|
48
|
+
error = body.get("error")
|
|
49
|
+
if isinstance(error, str):
|
|
50
|
+
detail = error
|
|
51
|
+
elif isinstance(error, dict) and isinstance(error.get("message"), str):
|
|
52
|
+
detail = error["message"]
|
|
53
|
+
if not detail and text and body is None:
|
|
54
|
+
detail = text[:200].strip() or None
|
|
55
|
+
status = response.status_code
|
|
56
|
+
return FoundgineHttpError(status, f"HTTP {status}: {detail}" if detail else f"HTTP {status}", body)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
async def ensure_success(response: httpx.Response) -> None:
|
|
60
|
+
if not response.is_success:
|
|
61
|
+
raise await error_for(response)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
async def await_or_cancel(awaitable: Awaitable[T], cancel: asyncio.Event | None) -> T:
|
|
65
|
+
"""Await ``awaitable``; if ``cancel`` is set first, cancel it and raise :class:`FoundgineAbortError`.
|
|
66
|
+
|
|
67
|
+
Cancelling the *calling* task cancels the inner work too and ``CancelledError`` propagates.
|
|
68
|
+
"""
|
|
69
|
+
if cancel is None:
|
|
70
|
+
return await awaitable
|
|
71
|
+
if cancel.is_set():
|
|
72
|
+
if inspect.iscoroutine(awaitable):
|
|
73
|
+
awaitable.close()
|
|
74
|
+
raise FoundgineAbortError()
|
|
75
|
+
work = asyncio.ensure_future(awaitable)
|
|
76
|
+
waiter = asyncio.ensure_future(cancel.wait())
|
|
77
|
+
try:
|
|
78
|
+
await asyncio.wait({work, waiter}, return_when=asyncio.FIRST_COMPLETED)
|
|
79
|
+
if work.done():
|
|
80
|
+
return work.result()
|
|
81
|
+
work.cancel()
|
|
82
|
+
await asyncio.gather(work, return_exceptions=True)
|
|
83
|
+
raise FoundgineAbortError()
|
|
84
|
+
finally:
|
|
85
|
+
waiter.cancel()
|
|
86
|
+
if not work.done():
|
|
87
|
+
work.cancel()
|