api-mapper-client 1.2.0__tar.gz → 1.3.0__tar.gz
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.
- {api_mapper_client-1.2.0 → api_mapper_client-1.3.0}/.gitignore +23 -0
- {api_mapper_client-1.2.0 → api_mapper_client-1.3.0}/PKG-INFO +3 -2
- {api_mapper_client-1.2.0 → api_mapper_client-1.3.0}/README.md +1 -0
- {api_mapper_client-1.2.0 → api_mapper_client-1.3.0}/api_mapper_client/__init__.py +20 -1
- api_mapper_client-1.3.0/api_mapper_client/agents.py +167 -0
- {api_mapper_client-1.2.0 → api_mapper_client-1.3.0}/api_mapper_client/client.py +25 -18
- api_mapper_client-1.3.0/api_mapper_client/contracts.py +179 -0
- api_mapper_client-1.3.0/api_mapper_client/webhooks.py +43 -0
- {api_mapper_client-1.2.0 → api_mapper_client-1.3.0}/pyproject.toml +6 -5
- api_mapper_client-1.2.0/api_mapper_client/contracts.py +0 -28
- {api_mapper_client-1.2.0 → api_mapper_client-1.3.0}/LICENSE +0 -0
- {api_mapper_client-1.2.0 → api_mapper_client-1.3.0}/api_mapper_client/auth/__init__.py +0 -0
- {api_mapper_client-1.2.0 → api_mapper_client-1.3.0}/api_mapper_client/auth/api_key.py +0 -0
- {api_mapper_client-1.2.0 → api_mapper_client-1.3.0}/api_mapper_client/auth/base.py +0 -0
- {api_mapper_client-1.2.0 → api_mapper_client-1.3.0}/api_mapper_client/auth/delegated_bearer.py +0 -0
- {api_mapper_client-1.2.0 → api_mapper_client-1.3.0}/api_mapper_client/auth/oauth2_client_credentials.py +0 -0
- {api_mapper_client-1.2.0 → api_mapper_client-1.3.0}/api_mapper_langchain/__init__.py +0 -0
- {api_mapper_client-1.2.0 → api_mapper_client-1.3.0}/api_mapper_langchain/toolkit.py +0 -0
- {api_mapper_client-1.2.0 → api_mapper_client-1.3.0}/api_mapper_langgraph/__init__.py +0 -0
- {api_mapper_client-1.2.0 → api_mapper_client-1.3.0}/api_mapper_langgraph/nodes.py +0 -0
|
@@ -223,6 +223,10 @@ pnpm-debug.log*
|
|
|
223
223
|
# Generated public site export
|
|
224
224
|
src/PublicSite/CodedProjects.AI.ApiMapper.Public.Web/wwwroot/
|
|
225
225
|
|
|
226
|
+
# License Admin BFF: the SPA build the publish script copies in, and the local Data Protection key ring (plan 0090)
|
|
227
|
+
src/LicenseAdminPortal/CodedProjects.AI.ApiMapper.LicenseAdminPortal.Web/wwwroot/
|
|
228
|
+
src/LicenseAdminPortal/CodedProjects.AI.ApiMapper.LicenseAdminPortal.Web/App_Data/
|
|
229
|
+
|
|
226
230
|
# NuGet Packages
|
|
227
231
|
*.nupkg
|
|
228
232
|
# NuGet Symbol Packages
|
|
@@ -436,3 +440,22 @@ opencode.json.*
|
|
|
436
440
|
!/releases/
|
|
437
441
|
/releases/*
|
|
438
442
|
!/releases/docs/
|
|
443
|
+
|
|
444
|
+
# Plan 0090. The local license folder the repository's compose files mount at /license (LICENSE_DIR). It holds an
|
|
445
|
+
# installation's license file and, in development, the throwaway key ring tools/licensing/create-dev-license.sh
|
|
446
|
+
# generates. A customer license names the customer and a development key ring is trust material for this machine
|
|
447
|
+
# only -- neither belongs in git. Not "license/": on a case-insensitive file system that is the LICENSE file.
|
|
448
|
+
# The trusted public keys the Runtime ships live in src/Runtime/.../Runtime.Host/licensing/public-keys/, not here.
|
|
449
|
+
/license-files/
|
|
450
|
+
|
|
451
|
+
# Plan 0090. The License Admin Portal's local development folder, written by tools/license-admin/setup-dev.sh: the
|
|
452
|
+
# throwaway evaluation signing key (PFX + .cer), the write-once archive, and the .NET dev certificate exported as PEM
|
|
453
|
+
# for the SPA dev server. Private keys for this machine only; never in git (gitleaks scans history).
|
|
454
|
+
/license-admin-dev/
|
|
455
|
+
|
|
456
|
+
#stale sonarqube files
|
|
457
|
+
.sonarqube.stale-*
|
|
458
|
+
|
|
459
|
+
# ZAP replacer configurations carry the scan session's credentials; never commit one, even redacted.
|
|
460
|
+
releases/**/zap-config.prop
|
|
461
|
+
releases/**/zap-runtime-config.prop
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: api-mapper-client
|
|
3
|
-
Version: 1.
|
|
3
|
+
Version: 1.3.0
|
|
4
4
|
Summary: Client SDK for the CodedProjects AI ApiMapper Runtime
|
|
5
5
|
Project-URL: Homepage, https://apimapper.ai
|
|
6
6
|
Author: Coded Projects
|
|
@@ -16,7 +16,7 @@ Classifier: Programming Language :: Python :: 3.12
|
|
|
16
16
|
Classifier: Programming Language :: Python :: 3.13
|
|
17
17
|
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
18
18
|
Requires-Python: >=3.12
|
|
19
|
-
Requires-Dist: httpx>=
|
|
19
|
+
Requires-Dist: httpx>=0.28.1
|
|
20
20
|
Provides-Extra: all
|
|
21
21
|
Requires-Dist: langchain-core>=1.3.3; extra == 'all'
|
|
22
22
|
Requires-Dist: langgraph>=1.0.10; extra == 'all'
|
|
@@ -58,6 +58,7 @@ pip install "api-mapper-client[all]"
|
|
|
58
58
|
- runtime system prompt loading,
|
|
59
59
|
- tool invocation over MCP-compatible HTTP endpoints,
|
|
60
60
|
- API key, delegated bearer token, and OAuth2 client credentials authentication helpers,
|
|
61
|
+
- on-demand hosted-agent executions (start, read, cancel) via `ApiMapperAgentClient`, and a webhook signing helper,
|
|
61
62
|
- optional LangChain and LangGraph integration helpers.
|
|
62
63
|
|
|
63
64
|
## Quick start
|
|
@@ -22,6 +22,7 @@ pip install "api-mapper-client[all]"
|
|
|
22
22
|
- runtime system prompt loading,
|
|
23
23
|
- tool invocation over MCP-compatible HTTP endpoints,
|
|
24
24
|
- API key, delegated bearer token, and OAuth2 client credentials authentication helpers,
|
|
25
|
+
- on-demand hosted-agent executions (start, read, cancel) via `ApiMapperAgentClient`, and a webhook signing helper,
|
|
25
26
|
- optional LangChain and LangGraph integration helpers.
|
|
26
27
|
|
|
27
28
|
## Quick start
|
|
@@ -1,13 +1,27 @@
|
|
|
1
1
|
from .client import ApiMapperClient, ApiMapperClientOptions, ApiMapperRequestError
|
|
2
|
+
from .agents import ApiMapperAgentClient, ApiMapperAgentRequestError
|
|
3
|
+
from .webhooks import AgentWebhookSignature
|
|
2
4
|
from .auth.api_key import ApiKeyCredentialProvider
|
|
3
5
|
from .auth.delegated_bearer import DelegatedBearerCredentialProvider
|
|
4
6
|
from .auth.oauth2_client_credentials import OAuth2ClientCredentialsProvider, OAuth2ClientCredentialsOptions
|
|
5
|
-
from .contracts import
|
|
7
|
+
from .contracts import (
|
|
8
|
+
AgentExecutionCancelResult,
|
|
9
|
+
AgentExecutionInfo,
|
|
10
|
+
AgentExecutionStarted,
|
|
11
|
+
AgentExecutionStartRequest,
|
|
12
|
+
AgentExecutionSummary,
|
|
13
|
+
McpTool,
|
|
14
|
+
McpToolCallResult,
|
|
15
|
+
McpToolContent,
|
|
16
|
+
)
|
|
6
17
|
|
|
7
18
|
__all__ = [
|
|
8
19
|
"ApiMapperClient",
|
|
9
20
|
"ApiMapperClientOptions",
|
|
10
21
|
"ApiMapperRequestError",
|
|
22
|
+
"ApiMapperAgentClient",
|
|
23
|
+
"ApiMapperAgentRequestError",
|
|
24
|
+
"AgentWebhookSignature",
|
|
11
25
|
"ApiKeyCredentialProvider",
|
|
12
26
|
"DelegatedBearerCredentialProvider",
|
|
13
27
|
"OAuth2ClientCredentialsProvider",
|
|
@@ -15,4 +29,9 @@ __all__ = [
|
|
|
15
29
|
"McpTool",
|
|
16
30
|
"McpToolCallResult",
|
|
17
31
|
"McpToolContent",
|
|
32
|
+
"AgentExecutionStartRequest",
|
|
33
|
+
"AgentExecutionStarted",
|
|
34
|
+
"AgentExecutionInfo",
|
|
35
|
+
"AgentExecutionSummary",
|
|
36
|
+
"AgentExecutionCancelResult",
|
|
18
37
|
]
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
"""On-demand hosted-agent executions through the Runtime's agent execution API."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import logging
|
|
5
|
+
import uuid
|
|
6
|
+
from datetime import timedelta
|
|
7
|
+
from typing import Any, Callable, TypeVar
|
|
8
|
+
|
|
9
|
+
import httpx
|
|
10
|
+
|
|
11
|
+
from .client import CORRELATION_ID_HEADER, ApiMapperClientOptions, resolve_correlation_id
|
|
12
|
+
from .contracts import (
|
|
13
|
+
AgentExecutionCancelResult,
|
|
14
|
+
AgentExecutionInfo,
|
|
15
|
+
AgentExecutionStarted,
|
|
16
|
+
AgentExecutionStartRequest,
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
# Auth header values (Bearer tokens, API keys) and the message sent to the agent are never logged.
|
|
20
|
+
logger = logging.getLogger(__name__)
|
|
21
|
+
|
|
22
|
+
T = TypeVar("T")
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class ApiMapperAgentRequestError(RuntimeError):
|
|
26
|
+
"""The Runtime's agent execution API refused a request.
|
|
27
|
+
|
|
28
|
+
``status_code`` is the HTTP status: 400 (bad input or preset), 403 (the agent's policy refuses
|
|
29
|
+
this caller), 404 (no such agent, or an execution this caller may not see), 409 (the agent is
|
|
30
|
+
unavailable) and 429 (the agent is at capacity — honour ``retry_after``). ``problem_type`` is the
|
|
31
|
+
problem type, such as ``urn:apimapper:agents:preset-not-found``, when the Runtime sent one.
|
|
32
|
+
"""
|
|
33
|
+
|
|
34
|
+
def __init__(
|
|
35
|
+
self,
|
|
36
|
+
operation: str,
|
|
37
|
+
status_code: int,
|
|
38
|
+
problem_type: str | None = None,
|
|
39
|
+
detail: str | None = None,
|
|
40
|
+
retry_after: timedelta | None = None,
|
|
41
|
+
) -> None:
|
|
42
|
+
suffix = "." if detail is None else f": {detail}"
|
|
43
|
+
super().__init__(f"Agent request '{operation}' failed with HTTP {status_code}{suffix}")
|
|
44
|
+
self.operation = operation
|
|
45
|
+
self.status_code = status_code
|
|
46
|
+
self.problem_type = problem_type
|
|
47
|
+
self.retry_after = retry_after
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class ApiMapperAgentClient:
|
|
51
|
+
"""Starts the tenant's hosted agents on demand, and reads or cancels what it started.
|
|
52
|
+
|
|
53
|
+
Calls ``{base_url}/runtime/{tenant_id}/agents/`` with the same :class:`ApiMapperClientOptions`
|
|
54
|
+
as :class:`ApiMapperClient` — base URL, tenant, credential and correlation ID provider; the
|
|
55
|
+
client id is not used. The agent runs as *this client's caller*: the agent's access policy
|
|
56
|
+
decides whether it may, exactly as for an A2A call, and a user token keeps its
|
|
57
|
+
delegated-credential semantics.
|
|
58
|
+
|
|
59
|
+
A refusal raises :class:`ApiMapperAgentRequestError`. Nothing is retried: starting an execution
|
|
60
|
+
is not idempotent, and a retried POST would start the agent twice.
|
|
61
|
+
"""
|
|
62
|
+
|
|
63
|
+
def __init__(self, opts: ApiMapperClientOptions) -> None:
|
|
64
|
+
self._opts = opts
|
|
65
|
+
self._agent_root = f"{opts.base_url.rstrip('/')}/runtime/{opts.tenant_id}/agents/"
|
|
66
|
+
# httpx retries nothing by default, which is what a non-idempotent start needs.
|
|
67
|
+
self._http = httpx.AsyncClient()
|
|
68
|
+
|
|
69
|
+
async def start_agent_execution(
|
|
70
|
+
self,
|
|
71
|
+
agent_id: uuid.UUID,
|
|
72
|
+
request: AgentExecutionStartRequest,
|
|
73
|
+
) -> AgentExecutionStarted:
|
|
74
|
+
"""Start ``agent_id`` with ``request``. Never retried: a retry would start the agent twice."""
|
|
75
|
+
started = await self._send(
|
|
76
|
+
"start", "POST", f"{agent_id}/executions", request.to_json(), AgentExecutionStarted.from_json
|
|
77
|
+
)
|
|
78
|
+
logger.info("Started execution %s of agent %s: %s.", started.execution_id, agent_id, started.status)
|
|
79
|
+
return started
|
|
80
|
+
|
|
81
|
+
async def get_agent_execution(self, execution_id: uuid.UUID) -> AgentExecutionInfo:
|
|
82
|
+
"""Read an execution this caller started, or one of an agent this caller may call."""
|
|
83
|
+
return await self._send("get", "GET", f"executions/{execution_id}", None, AgentExecutionInfo.from_json)
|
|
84
|
+
|
|
85
|
+
async def cancel_agent_execution(self, execution_id: uuid.UUID) -> AgentExecutionCancelResult:
|
|
86
|
+
"""Cancel an execution this caller may see."""
|
|
87
|
+
result = await self._send(
|
|
88
|
+
"cancel", "POST", f"executions/{execution_id}/cancel", None, AgentExecutionCancelResult.from_json
|
|
89
|
+
)
|
|
90
|
+
logger.info("Cancel of execution %s: %s.", execution_id, result.outcome)
|
|
91
|
+
return result
|
|
92
|
+
|
|
93
|
+
async def close(self) -> None:
|
|
94
|
+
await self._http.aclose()
|
|
95
|
+
|
|
96
|
+
async def __aenter__(self) -> "ApiMapperAgentClient":
|
|
97
|
+
return self
|
|
98
|
+
|
|
99
|
+
async def __aexit__(self, *_: Any) -> None:
|
|
100
|
+
await self.close()
|
|
101
|
+
|
|
102
|
+
# ── Internals ─────────────────────────────────────────────────────────
|
|
103
|
+
|
|
104
|
+
async def _send(
|
|
105
|
+
self,
|
|
106
|
+
operation: str,
|
|
107
|
+
method: str,
|
|
108
|
+
path: str,
|
|
109
|
+
body: dict[str, Any] | None,
|
|
110
|
+
parse: Callable[[dict[str, Any]], T],
|
|
111
|
+
) -> T:
|
|
112
|
+
headers: dict[str, str] = {"Accept": "application/json"}
|
|
113
|
+
correlation_id = resolve_correlation_id(self._opts, None)
|
|
114
|
+
if correlation_id:
|
|
115
|
+
headers[CORRELATION_ID_HEADER] = correlation_id
|
|
116
|
+
# Credential provider adds auth headers — values are never logged.
|
|
117
|
+
await self._opts.credentials.enrich(headers)
|
|
118
|
+
|
|
119
|
+
response = await self._http.request(method, self._agent_root + path, headers=headers, json=body)
|
|
120
|
+
if not response.is_success:
|
|
121
|
+
raise self._refusal(operation, response)
|
|
122
|
+
|
|
123
|
+
try:
|
|
124
|
+
payload = response.json() if response.content else None
|
|
125
|
+
if not isinstance(payload, dict):
|
|
126
|
+
raise ApiMapperAgentRequestError(
|
|
127
|
+
operation, response.status_code, None, "The Runtime returned an empty body."
|
|
128
|
+
)
|
|
129
|
+
return parse(payload)
|
|
130
|
+
except (ValueError, KeyError, TypeError) as error:
|
|
131
|
+
raise ApiMapperAgentRequestError(
|
|
132
|
+
operation, response.status_code, None, f"The Runtime returned a body that could not be read: {error}"
|
|
133
|
+
) from error
|
|
134
|
+
|
|
135
|
+
@staticmethod
|
|
136
|
+
def _refusal(operation: str, response: httpx.Response) -> ApiMapperAgentRequestError:
|
|
137
|
+
problem = _read_problem(response)
|
|
138
|
+
problem_type = _text_or_none(problem, "type")
|
|
139
|
+
# A route refusal is problem+json and says why in 'detail'. A start the agent refused (403,
|
|
140
|
+
# 409, 429) answers with the start response instead, whose 'failureReason' says why.
|
|
141
|
+
detail = _text_or_none(problem, "detail") or _text_or_none(problem, "failureReason")
|
|
142
|
+
logger.warning(
|
|
143
|
+
"Agent request '%s' was refused with HTTP %d (%s).", operation, response.status_code, problem_type
|
|
144
|
+
)
|
|
145
|
+
return ApiMapperAgentRequestError(
|
|
146
|
+
operation, response.status_code, problem_type, detail, _retry_after(response)
|
|
147
|
+
)
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def _read_problem(response: httpx.Response) -> dict[str, Any] | None:
|
|
151
|
+
try:
|
|
152
|
+
payload = response.json() if response.content else None
|
|
153
|
+
except ValueError:
|
|
154
|
+
# A refusal from the Gateway or a proxy may not be JSON; the status still says what happened.
|
|
155
|
+
return None
|
|
156
|
+
return payload if isinstance(payload, dict) else None
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def _text_or_none(problem: dict[str, Any] | None, key: str) -> str | None:
|
|
160
|
+
value = (problem or {}).get(key)
|
|
161
|
+
return value if isinstance(value, str) else None
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def _retry_after(response: httpx.Response) -> timedelta | None:
|
|
165
|
+
"""The ``Retry-After`` delay in seconds, as the Runtime sends it; ``None`` when absent or a date."""
|
|
166
|
+
value = (response.headers.get("Retry-After") or "").strip()
|
|
167
|
+
return timedelta(seconds=int(value)) if value.isascii() and value.isdigit() else None
|
|
@@ -86,6 +86,30 @@ class ApiMapperClientOptions:
|
|
|
86
86
|
"""
|
|
87
87
|
|
|
88
88
|
|
|
89
|
+
def resolve_correlation_id(
|
|
90
|
+
opts: ApiMapperClientOptions,
|
|
91
|
+
explicit_correlation_id: str | None,
|
|
92
|
+
) -> str | None:
|
|
93
|
+
"""Resolve the correlation ID for a request; shared by the tool client and the agent client.
|
|
94
|
+
|
|
95
|
+
An explicit per-call value wins over the configured provider. A provider that raises must
|
|
96
|
+
not fail the call.
|
|
97
|
+
"""
|
|
98
|
+
if explicit_correlation_id and explicit_correlation_id.strip():
|
|
99
|
+
return explicit_correlation_id.strip()
|
|
100
|
+
|
|
101
|
+
if opts.correlation_id_provider is None:
|
|
102
|
+
return None
|
|
103
|
+
|
|
104
|
+
try:
|
|
105
|
+
provided = opts.correlation_id_provider()
|
|
106
|
+
except Exception:
|
|
107
|
+
logger.warning("correlation_id_provider raised; continuing without a correlation ID.", exc_info=True)
|
|
108
|
+
return None
|
|
109
|
+
|
|
110
|
+
return provided.strip() if provided and provided.strip() else None
|
|
111
|
+
|
|
112
|
+
|
|
89
113
|
def _parse_sse_frame(raw_frame: str) -> dict[str, Any] | None:
|
|
90
114
|
"""Parse a single ``\\n``-terminated-line SSE frame (no trailing blank line).
|
|
91
115
|
|
|
@@ -588,24 +612,7 @@ class ApiMapperClient:
|
|
|
588
612
|
self._session_id = sid
|
|
589
613
|
|
|
590
614
|
def _resolve_correlation_id(self, explicit_correlation_id: str | None) -> str | None:
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
An explicit per-call value wins over the configured provider. A provider that raises must
|
|
594
|
-
not fail the tool call.
|
|
595
|
-
"""
|
|
596
|
-
if explicit_correlation_id and explicit_correlation_id.strip():
|
|
597
|
-
return explicit_correlation_id.strip()
|
|
598
|
-
|
|
599
|
-
if self._opts.correlation_id_provider is None:
|
|
600
|
-
return None
|
|
601
|
-
|
|
602
|
-
try:
|
|
603
|
-
provided = self._opts.correlation_id_provider()
|
|
604
|
-
except Exception:
|
|
605
|
-
logger.warning("correlation_id_provider raised; continuing without a correlation ID.", exc_info=True)
|
|
606
|
-
return None
|
|
607
|
-
|
|
608
|
-
return provided.strip() if provided and provided.strip() else None
|
|
615
|
+
return resolve_correlation_id(self._opts, explicit_correlation_id)
|
|
609
616
|
|
|
610
617
|
def _warn_if_correlation_id_rejected(
|
|
611
618
|
self,
|
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
import uuid
|
|
2
|
+
from dataclasses import dataclass, field
|
|
3
|
+
from datetime import datetime
|
|
4
|
+
from typing import Any
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
@dataclass
|
|
8
|
+
class McpToolContent:
|
|
9
|
+
type: str
|
|
10
|
+
text: str | None = None
|
|
11
|
+
data: Any = None
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@dataclass
|
|
15
|
+
class McpTool:
|
|
16
|
+
name: str
|
|
17
|
+
description: str | None
|
|
18
|
+
input_schema: dict[str, Any]
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@dataclass
|
|
22
|
+
class McpToolCallResult:
|
|
23
|
+
content: list[McpToolContent] = field(default_factory=list)
|
|
24
|
+
structured_content: Any = None
|
|
25
|
+
is_error: bool | None = None
|
|
26
|
+
|
|
27
|
+
def to_text(self) -> str:
|
|
28
|
+
return "\n\n".join(
|
|
29
|
+
c.text.strip() for c in self.content if c.type == "text" and c.text and c.text.strip()
|
|
30
|
+
)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
# ── Hosted-agent executions ───────────────────────────────────────────────────
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _uuid_or_none(value: Any) -> uuid.UUID | None:
|
|
37
|
+
return uuid.UUID(value) if value else None
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _datetime_or_none(value: Any) -> datetime | None:
|
|
41
|
+
return datetime.fromisoformat(value) if value else None
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
@dataclass
|
|
45
|
+
class AgentExecutionStartRequest:
|
|
46
|
+
"""Starts a hosted agent on demand.
|
|
47
|
+
|
|
48
|
+
``text`` is your message to the agent, required unless ``trigger_id`` names a *Manual* preset of
|
|
49
|
+
the agent to start from (its instructions, parameters and limits). ``parameters`` is a JSON object
|
|
50
|
+
whose keys win over the preset's. ``return_immediately`` answers as soon as the execution exists
|
|
51
|
+
(the default), or waits for the agent's turn to settle and returns its answer.
|
|
52
|
+
"""
|
|
53
|
+
|
|
54
|
+
text: str | None = None
|
|
55
|
+
trigger_id: uuid.UUID | None = None
|
|
56
|
+
parameters: dict[str, Any] | None = None
|
|
57
|
+
return_immediately: bool = True
|
|
58
|
+
|
|
59
|
+
def to_json(self) -> dict[str, Any]:
|
|
60
|
+
body: dict[str, Any] = {"returnImmediately": self.return_immediately}
|
|
61
|
+
if self.text is not None:
|
|
62
|
+
body["text"] = self.text
|
|
63
|
+
if self.trigger_id is not None:
|
|
64
|
+
body["triggerId"] = str(self.trigger_id)
|
|
65
|
+
if self.parameters is not None:
|
|
66
|
+
body["parameters"] = self.parameters
|
|
67
|
+
return body
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
@dataclass
|
|
71
|
+
class AgentExecutionStarted:
|
|
72
|
+
"""What starting an execution produced.
|
|
73
|
+
|
|
74
|
+
``execution_id`` is what to pass to ``get_agent_execution`` or ``cancel_agent_execution``.
|
|
75
|
+
``status`` is the A2A task state: ``TASK_STATE_SUBMITTED`` when not waiting, the settled state
|
|
76
|
+
otherwise. ``result_text`` is the agent's answer when the call waited and the agent completed;
|
|
77
|
+
``failure_reason`` says why the execution failed, when it did.
|
|
78
|
+
"""
|
|
79
|
+
|
|
80
|
+
execution_id: uuid.UUID | None
|
|
81
|
+
task_id: str
|
|
82
|
+
status: str
|
|
83
|
+
result_text: str | None = None
|
|
84
|
+
failure_reason: str | None = None
|
|
85
|
+
|
|
86
|
+
@classmethod
|
|
87
|
+
def from_json(cls, data: dict[str, Any]) -> "AgentExecutionStarted":
|
|
88
|
+
return cls(
|
|
89
|
+
execution_id=_uuid_or_none(data.get("executionId")),
|
|
90
|
+
task_id=data.get("taskId", ""),
|
|
91
|
+
status=data.get("status", ""),
|
|
92
|
+
result_text=data.get("resultText"),
|
|
93
|
+
failure_reason=data.get("failureReason"),
|
|
94
|
+
)
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
@dataclass
|
|
98
|
+
class AgentExecutionSummary:
|
|
99
|
+
"""An execution's status, timings and accounting.
|
|
100
|
+
|
|
101
|
+
``status`` is the execution's own state — ``Queued``, ``Running``, ``Completed``, ``Failed``,
|
|
102
|
+
``Cancelled`` and the rest — not the A2A task state.
|
|
103
|
+
"""
|
|
104
|
+
|
|
105
|
+
id: uuid.UUID
|
|
106
|
+
registered_agent_id: uuid.UUID
|
|
107
|
+
trigger_id: uuid.UUID | None
|
|
108
|
+
channel: str
|
|
109
|
+
status: str
|
|
110
|
+
failure_kind: str | None
|
|
111
|
+
status_reason: str | None
|
|
112
|
+
task_id: str | None
|
|
113
|
+
correlation_id: str
|
|
114
|
+
attempt: int
|
|
115
|
+
accepted_at_utc: datetime
|
|
116
|
+
started_at_utc: datetime | None
|
|
117
|
+
ended_at_utc: datetime | None
|
|
118
|
+
tool_call_count: int
|
|
119
|
+
input_tokens: int
|
|
120
|
+
output_tokens: int
|
|
121
|
+
|
|
122
|
+
@classmethod
|
|
123
|
+
def from_json(cls, data: dict[str, Any]) -> "AgentExecutionSummary":
|
|
124
|
+
return cls(
|
|
125
|
+
id=uuid.UUID(data["id"]),
|
|
126
|
+
registered_agent_id=uuid.UUID(data["registeredAgentId"]),
|
|
127
|
+
trigger_id=_uuid_or_none(data.get("triggerId")),
|
|
128
|
+
channel=data.get("channel", ""),
|
|
129
|
+
status=data.get("status", ""),
|
|
130
|
+
failure_kind=data.get("failureKind"),
|
|
131
|
+
status_reason=data.get("statusReason"),
|
|
132
|
+
task_id=data.get("taskId"),
|
|
133
|
+
correlation_id=data.get("correlationId", ""),
|
|
134
|
+
attempt=data.get("attempt", 0),
|
|
135
|
+
accepted_at_utc=datetime.fromisoformat(data["acceptedAtUtc"]),
|
|
136
|
+
started_at_utc=_datetime_or_none(data.get("startedAtUtc")),
|
|
137
|
+
ended_at_utc=_datetime_or_none(data.get("endedAtUtc")),
|
|
138
|
+
tool_call_count=data.get("toolCallCount", 0),
|
|
139
|
+
input_tokens=data.get("inputTokens", 0),
|
|
140
|
+
output_tokens=data.get("outputTokens", 0),
|
|
141
|
+
)
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
@dataclass
|
|
145
|
+
class AgentExecutionInfo:
|
|
146
|
+
"""An execution and its result.
|
|
147
|
+
|
|
148
|
+
``result_text`` is the agent's answer, once it completed and while the result is retained;
|
|
149
|
+
``result_retained`` is ``False`` when the result has passed its retention and is no longer
|
|
150
|
+
available.
|
|
151
|
+
"""
|
|
152
|
+
|
|
153
|
+
execution: AgentExecutionSummary
|
|
154
|
+
result_text: str | None
|
|
155
|
+
result_retained: bool
|
|
156
|
+
|
|
157
|
+
@classmethod
|
|
158
|
+
def from_json(cls, data: dict[str, Any]) -> "AgentExecutionInfo":
|
|
159
|
+
return cls(
|
|
160
|
+
execution=AgentExecutionSummary.from_json(data["execution"]),
|
|
161
|
+
result_text=data.get("resultText"),
|
|
162
|
+
result_retained=bool(data.get("resultRetained", False)),
|
|
163
|
+
)
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
@dataclass
|
|
167
|
+
class AgentExecutionCancelResult:
|
|
168
|
+
"""The answer to a cancel request.
|
|
169
|
+
|
|
170
|
+
``outcome`` is ``Cancelled`` (it had not started), ``Requested`` (its turn stops within
|
|
171
|
+
seconds), or ``AlreadyEnded``.
|
|
172
|
+
"""
|
|
173
|
+
|
|
174
|
+
execution_id: uuid.UUID
|
|
175
|
+
outcome: str
|
|
176
|
+
|
|
177
|
+
@classmethod
|
|
178
|
+
def from_json(cls, data: dict[str, Any]) -> "AgentExecutionCancelResult":
|
|
179
|
+
return cls(execution_id=uuid.UUID(data["executionId"]), outcome=data.get("outcome", ""))
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
"""Signing deliveries to hosted-agent webhook triggers."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import hashlib
|
|
5
|
+
import hmac
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class AgentWebhookSignature:
|
|
9
|
+
"""Signs a delivery to a hosted-agent webhook trigger with the trigger's signing secret.
|
|
10
|
+
|
|
11
|
+
For a sender you write yourself: GitHub and Jira Cloud sign their own deliveries, so you only
|
|
12
|
+
need this for the *ApiMapper v1* profile. Sign the exact bytes you send — the Runtime verifies
|
|
13
|
+
the body as received, before parsing it::
|
|
14
|
+
|
|
15
|
+
body = json.dumps(payload).encode("utf-8")
|
|
16
|
+
timestamp = int(time.time())
|
|
17
|
+
headers = {
|
|
18
|
+
"Content-Type": "application/json",
|
|
19
|
+
AgentWebhookSignature.TIMESTAMP_HEADER: str(timestamp),
|
|
20
|
+
AgentWebhookSignature.SIGNATURE_HEADER: AgentWebhookSignature.api_mapper_v1(secret, timestamp, body),
|
|
21
|
+
}
|
|
22
|
+
await http.post(webhook_url, content=body, headers=headers)
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
#: The header carrying the delivery's timestamp, in Unix seconds.
|
|
26
|
+
TIMESTAMP_HEADER = "X-ApiMapper-Timestamp"
|
|
27
|
+
|
|
28
|
+
#: The header carrying the signature.
|
|
29
|
+
SIGNATURE_HEADER = "X-ApiMapper-Signature"
|
|
30
|
+
|
|
31
|
+
@staticmethod
|
|
32
|
+
def api_mapper_v1(secret: str, unix_timestamp: int, body: bytes | str) -> str:
|
|
33
|
+
"""The *ApiMapper v1* signature of ``body`` at ``unix_timestamp``.
|
|
34
|
+
|
|
35
|
+
``v1=hex(HMAC-SHA256(secret, "{timestamp}.{body}"))``. A ``str`` body is signed as its UTF-8
|
|
36
|
+
bytes. The timestamp must be within five minutes of the Runtime's clock.
|
|
37
|
+
"""
|
|
38
|
+
if not secret:
|
|
39
|
+
raise ValueError("secret must not be empty.")
|
|
40
|
+
|
|
41
|
+
payload = body.encode("utf-8") if isinstance(body, str) else bytes(body)
|
|
42
|
+
signed = f"{int(unix_timestamp)}.".encode("utf-8") + payload
|
|
43
|
+
return "v1=" + hmac.new(secret.encode("utf-8"), signed, hashlib.sha256).hexdigest()
|
|
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "api-mapper-client"
|
|
7
|
-
version = "1.
|
|
7
|
+
version = "1.3.0"
|
|
8
8
|
description = "Client SDK for the CodedProjects AI ApiMapper Runtime"
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
license = "MIT"
|
|
@@ -13,10 +13,11 @@ authors = [
|
|
|
13
13
|
]
|
|
14
14
|
requires-python = ">=3.12"
|
|
15
15
|
dependencies = [
|
|
16
|
-
#
|
|
17
|
-
# GHSA-f2fp-rgf2-35cp,
|
|
18
|
-
#
|
|
19
|
-
|
|
16
|
+
# 0.28.1 is the current httpx release and has no known advisory. The five GHSAs a scan once reported
|
|
17
|
+
# here (GHSA-7mj9-2mp8-4m2p, -8xx6-hgc6-gc2m, -f2fp-rgf2-35cp, -pf96-p4fj-6566, -h4x7-gw46-3wm6) are
|
|
18
|
+
# for the separate httpx2 package, whose 2.x versions were mistaken for httpx's: a floor of
|
|
19
|
+
# httpx>=2.12.0 asked for a release that does not exist and made this package uninstallable.
|
|
20
|
+
"httpx>=0.28.1",
|
|
20
21
|
]
|
|
21
22
|
keywords = ["ai", "mcp", "apimapper", "llm", "tools", "python", "sdk", "client"]
|
|
22
23
|
classifiers = [
|
|
@@ -1,28 +0,0 @@
|
|
|
1
|
-
from dataclasses import dataclass, field
|
|
2
|
-
from typing import Any
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
@dataclass
|
|
6
|
-
class McpToolContent:
|
|
7
|
-
type: str
|
|
8
|
-
text: str | None = None
|
|
9
|
-
data: Any = None
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
@dataclass
|
|
13
|
-
class McpTool:
|
|
14
|
-
name: str
|
|
15
|
-
description: str | None
|
|
16
|
-
input_schema: dict[str, Any]
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
@dataclass
|
|
20
|
-
class McpToolCallResult:
|
|
21
|
-
content: list[McpToolContent] = field(default_factory=list)
|
|
22
|
-
structured_content: Any = None
|
|
23
|
-
is_error: bool | None = None
|
|
24
|
-
|
|
25
|
-
def to_text(self) -> str:
|
|
26
|
-
return "\n\n".join(
|
|
27
|
-
c.text.strip() for c in self.content if c.type == "text" and c.text and c.text.strip()
|
|
28
|
-
)
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
{api_mapper_client-1.2.0 → api_mapper_client-1.3.0}/api_mapper_client/auth/delegated_bearer.py
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|