tenxyte-mcp-server 0.1.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.
@@ -0,0 +1,114 @@
1
+ # Python
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+ *.so
6
+ .Python
7
+ build/
8
+ develop-eggs/
9
+ dist/
10
+ downloads/
11
+ eggs/
12
+ .eggs/
13
+ lib/
14
+ lib64/
15
+ parts/
16
+ sdist/
17
+ var/
18
+ wheels/
19
+ pip-wheel-metadata/
20
+ share/python-wheels/
21
+ *.egg-info/
22
+ .installed.cfg
23
+ *.egg
24
+ MANIFEST
25
+
26
+ # Virtual environments
27
+ venv/
28
+ ENV/
29
+ env/
30
+ .venv
31
+
32
+ # IDE
33
+ .vscode/
34
+ .idea/
35
+ *.swp
36
+ *.swo
37
+ *~
38
+
39
+ # Testing
40
+ .coverage
41
+ .coverage.*
42
+ htmlcov/
43
+ .pytest_cache/
44
+ .tox/
45
+ .nox/
46
+ coverage.xml
47
+ *.cover
48
+
49
+ checklist.md
50
+ log.md
51
+ site
52
+ site/*
53
+
54
+ next-steps.md
55
+ next-steps-phases.md
56
+
57
+ # Django
58
+ *.log
59
+ local_settings.py
60
+ db.sqlite3
61
+ db.sqlite3-journal
62
+ media/
63
+ staticfiles/
64
+
65
+ # Jupyter Notebook
66
+ .ipynb_checkpoints
67
+
68
+ # pyenv
69
+ .python-version
70
+
71
+ # mypy
72
+ .mypy_cache/
73
+ .dmypy.json
74
+ dmypy.json
75
+
76
+ # Pyre type checker
77
+ .pyre/
78
+
79
+ # OS
80
+ .DS_Store
81
+ Thumbs.db
82
+
83
+ # Distribution / packaging
84
+ *.tar.gz
85
+ *.whl
86
+
87
+ old_dists/
88
+ old_dists/*
89
+ old_dists/*/*
90
+
91
+ # Hypothesis
92
+ .hypothesis/
93
+
94
+ /plan
95
+ logs
96
+
97
+ # AIRS Conformance Suite ephemeral CI instance (spec z_aud_2)
98
+ spec/airs/conformance/tenxyte_ci/_ephemeral.sqlite3
99
+ spec/airs/conformance/tenxyte_ci/_ci_info.json
100
+
101
+ # AIRS Conformance Suite ephemeral FastAPI CI instance (spec z_aud_3, Wave F, task 9.2)
102
+ spec/airs/conformance/tenxyte_ci_fastapi/_ephemeral.sqlite3
103
+ spec/airs/conformance/tenxyte_ci_fastapi/_ci_info.json
104
+
105
+ # AIRS benchmark raw output (RESULTS.md is the canonical human-readable record)
106
+ benchmarks/airs/results_*.json
107
+
108
+ # js-contract-backend ephemeral demo instance (spec z_aud_3, task 14.2) — written to the current
109
+ # working directory wherever seed_and_serve.py is launched from (repo root when run directly,
110
+ # /app inside the container), recreated on every run, same convention as the AIRS Conformance
111
+ # Suite's own ephemeral instances above.
112
+ js-contract-backend.db
113
+
114
+ manual_tests
@@ -0,0 +1,107 @@
1
+ Metadata-Version: 2.5
2
+ Name: tenxyte-mcp-server
3
+ Version: 0.1.0
4
+ Summary: MCP server exposing AIRS/1.0 Agent Token upkeep (status, heartbeat, usage reporting, pending actions) as tools for MCP clients such as Claude Desktop. Pure HTTP client, no dependency on the tenxyte package.
5
+ Project-URL: Homepage, https://github.com/tenxyte/tenxyte
6
+ Project-URL: Specification, https://github.com/tenxyte/tenxyte/blob/main/spec/airs/AIRS-1.0.md
7
+ Project-URL: Documentation, https://github.com/tenxyte/tenxyte/tree/main/integrations/mcp-server
8
+ Author: Tenxyte
9
+ License-Expression: MIT
10
+ Keywords: agent-identity,ai-agents,airs,claude-desktop,mcp,model-context-protocol
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: License :: OSI Approved :: MIT License
14
+ Classifier: Operating System :: OS Independent
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Topic :: Security
21
+ Requires-Python: >=3.10
22
+ Requires-Dist: httpx>=0.27
23
+ Requires-Dist: mcp>=2.0
24
+ Provides-Extra: dev
25
+ Requires-Dist: black==26.5.1; extra == 'dev'
26
+ Requires-Dist: hypothesis>=6.0; extra == 'dev'
27
+ Requires-Dist: pytest-asyncio>=0.24; extra == 'dev'
28
+ Requires-Dist: pytest>=8.0; extra == 'dev'
29
+ Requires-Dist: respx>=0.21; extra == 'dev'
30
+ Requires-Dist: ruff==0.16.7; extra == 'dev'
31
+ Description-Content-Type: text/markdown
32
+
33
+ # tenxyte-mcp-server
34
+
35
+ An MCP (Model Context Protocol) server exposing [AIRS/1.0](../../spec/airs/AIRS-1.0.md) Agent
36
+ Token upkeep — status, heartbeat, usage reporting, pending actions, discovery — as tools any MCP
37
+ client (Claude Desktop and others) can call. A pure HTTP client: it never imports the `tenxyte`
38
+ package and works against any AIRS-conformant server.
39
+
40
+ ## Install & run
41
+
42
+ ```bash
43
+ uvx tenxyte-mcp-server
44
+ ```
45
+
46
+ or `pip install tenxyte-mcp-server && tenxyte-mcp-server`.
47
+
48
+ ## Environment variables
49
+
50
+ | Variable | Required | Purpose |
51
+ |---|---|---|
52
+ | `TENXYTE_BASE_URL` | Yes | Base URL of the AIRS-hosting API (e.g. `https://your-server.example.com/api/v1/auth`). |
53
+ | `TENXYTE_AGENT_TOKEN` | Yes | The raw Agent Token value, issued once by a human via Tenxyte's own API. This server never creates tokens itself. |
54
+ | `TENXYTE_AGENT_TOKEN_ID` | Recommended | The token's id (returned alongside the raw value at issuance). Tenxyte's `heartbeat`/`report_usage` endpoints are addressed by id, not by the raw token — omit this and `airs_heartbeat`/`airs_report_usage` return a structured `MISSING_TOKEN_ID` error instead of guessing. |
55
+ | `TENXYTE_ACCESS_KEY` | No | Application `X-Access-Key`, if your Tenxyte deployment requires one. |
56
+ | `TENXYTE_ACCESS_SECRET` | No | Application `X-Access-Secret`, paired with the above. |
57
+
58
+ Missing `TENXYTE_BASE_URL` or `TENXYTE_AGENT_TOKEN` fails fast at startup — an explicit message
59
+ on stderr and a non-zero exit code, never a partial/degraded start.
60
+
61
+ ## Tools
62
+
63
+ | Tool | Maps to | Notes |
64
+ |---|---|---|
65
+ | `airs_discovery()` | `GET .../.well-known/airs/` | Capabilities only — spec version, active Conformance Levels, endpoint map, limits. |
66
+ | `airs_token_status()` | `POST .../heartbeat/` | No dedicated status endpoint exists in AIRS/1.0; this sends a heartbeat and reports the result — the one agent-callable operation that reveals liveness. |
67
+ | `airs_heartbeat()` | `POST .../heartbeat/` | Maintains the Dead Man's Switch Guardrail. |
68
+ | `airs_report_usage(cost_usd, prompt_tokens=0, completion_tokens=0)` | `POST .../report-usage/` | Reports LLM cost/usage against the token's budget. |
69
+ | `airs_list_pending_actions()` | `GET .../pending-actions/` | Tenxyte's reference implementation currently scopes this to the Delegating User's own human authentication — expect a structured `PERMISSION_DENIED`-shaped error against Tenxyte specifically; kept for AIRS/1.0 servers that do expose it to the agent side. |
70
+
71
+ Every tool that fails (suspended, revoked, expired token; a capability the server doesn't
72
+ announce) raises a structured error — a JSON-shaped message carrying `code`/`reason` — rather
73
+ than crashing the server process (spec/airs/AIRS-1.0.md §8, Requirement 5.5).
74
+
75
+ **Deliberately absent** (No_Privilege_Amplification_Rule, design.md D3): no tool creates an
76
+ Agent Token, and no tool confirms or denies a HITL Pending Action. Both stay strictly on the
77
+ human side of Tenxyte's own API — this server never holds a human credential.
78
+
79
+ ## Claude Desktop configuration
80
+
81
+ Add to `claude_desktop_config.json`:
82
+
83
+ ```json
84
+ {
85
+ "mcpServers": {
86
+ "tenxyte-airs": {
87
+ "command": "uvx",
88
+ "args": ["tenxyte-mcp-server"],
89
+ "env": {
90
+ "TENXYTE_BASE_URL": "https://your-server.example.com/api/v1/auth",
91
+ "TENXYTE_AGENT_TOKEN": "the-raw-token-value-returned-at-issuance",
92
+ "TENXYTE_AGENT_TOKEN_ID": "42"
93
+ }
94
+ }
95
+ }
96
+ }
97
+ ```
98
+
99
+ ## Resources
100
+
101
+ - `airs://token/status` — read-only mirror of `airs_token_status()`.
102
+ - `airs://budget` — the discovery document's active Conformance Levels and configured limits.
103
+
104
+ ## License
105
+
106
+ MIT (this package). The AIRS/1.0 specification it implements is separately licensed CC BY 4.0 —
107
+ see [`spec/airs/LICENSE`](../../spec/airs/LICENSE).
@@ -0,0 +1,75 @@
1
+ # tenxyte-mcp-server
2
+
3
+ An MCP (Model Context Protocol) server exposing [AIRS/1.0](../../spec/airs/AIRS-1.0.md) Agent
4
+ Token upkeep — status, heartbeat, usage reporting, pending actions, discovery — as tools any MCP
5
+ client (Claude Desktop and others) can call. A pure HTTP client: it never imports the `tenxyte`
6
+ package and works against any AIRS-conformant server.
7
+
8
+ ## Install & run
9
+
10
+ ```bash
11
+ uvx tenxyte-mcp-server
12
+ ```
13
+
14
+ or `pip install tenxyte-mcp-server && tenxyte-mcp-server`.
15
+
16
+ ## Environment variables
17
+
18
+ | Variable | Required | Purpose |
19
+ |---|---|---|
20
+ | `TENXYTE_BASE_URL` | Yes | Base URL of the AIRS-hosting API (e.g. `https://your-server.example.com/api/v1/auth`). |
21
+ | `TENXYTE_AGENT_TOKEN` | Yes | The raw Agent Token value, issued once by a human via Tenxyte's own API. This server never creates tokens itself. |
22
+ | `TENXYTE_AGENT_TOKEN_ID` | Recommended | The token's id (returned alongside the raw value at issuance). Tenxyte's `heartbeat`/`report_usage` endpoints are addressed by id, not by the raw token — omit this and `airs_heartbeat`/`airs_report_usage` return a structured `MISSING_TOKEN_ID` error instead of guessing. |
23
+ | `TENXYTE_ACCESS_KEY` | No | Application `X-Access-Key`, if your Tenxyte deployment requires one. |
24
+ | `TENXYTE_ACCESS_SECRET` | No | Application `X-Access-Secret`, paired with the above. |
25
+
26
+ Missing `TENXYTE_BASE_URL` or `TENXYTE_AGENT_TOKEN` fails fast at startup — an explicit message
27
+ on stderr and a non-zero exit code, never a partial/degraded start.
28
+
29
+ ## Tools
30
+
31
+ | Tool | Maps to | Notes |
32
+ |---|---|---|
33
+ | `airs_discovery()` | `GET .../.well-known/airs/` | Capabilities only — spec version, active Conformance Levels, endpoint map, limits. |
34
+ | `airs_token_status()` | `POST .../heartbeat/` | No dedicated status endpoint exists in AIRS/1.0; this sends a heartbeat and reports the result — the one agent-callable operation that reveals liveness. |
35
+ | `airs_heartbeat()` | `POST .../heartbeat/` | Maintains the Dead Man's Switch Guardrail. |
36
+ | `airs_report_usage(cost_usd, prompt_tokens=0, completion_tokens=0)` | `POST .../report-usage/` | Reports LLM cost/usage against the token's budget. |
37
+ | `airs_list_pending_actions()` | `GET .../pending-actions/` | Tenxyte's reference implementation currently scopes this to the Delegating User's own human authentication — expect a structured `PERMISSION_DENIED`-shaped error against Tenxyte specifically; kept for AIRS/1.0 servers that do expose it to the agent side. |
38
+
39
+ Every tool that fails (suspended, revoked, expired token; a capability the server doesn't
40
+ announce) raises a structured error — a JSON-shaped message carrying `code`/`reason` — rather
41
+ than crashing the server process (spec/airs/AIRS-1.0.md §8, Requirement 5.5).
42
+
43
+ **Deliberately absent** (No_Privilege_Amplification_Rule, design.md D3): no tool creates an
44
+ Agent Token, and no tool confirms or denies a HITL Pending Action. Both stay strictly on the
45
+ human side of Tenxyte's own API — this server never holds a human credential.
46
+
47
+ ## Claude Desktop configuration
48
+
49
+ Add to `claude_desktop_config.json`:
50
+
51
+ ```json
52
+ {
53
+ "mcpServers": {
54
+ "tenxyte-airs": {
55
+ "command": "uvx",
56
+ "args": ["tenxyte-mcp-server"],
57
+ "env": {
58
+ "TENXYTE_BASE_URL": "https://your-server.example.com/api/v1/auth",
59
+ "TENXYTE_AGENT_TOKEN": "the-raw-token-value-returned-at-issuance",
60
+ "TENXYTE_AGENT_TOKEN_ID": "42"
61
+ }
62
+ }
63
+ }
64
+ }
65
+ ```
66
+
67
+ ## Resources
68
+
69
+ - `airs://token/status` — read-only mirror of `airs_token_status()`.
70
+ - `airs://budget` — the discovery document's active Conformance Levels and configured limits.
71
+
72
+ ## License
73
+
74
+ MIT (this package). The AIRS/1.0 specification it implements is separately licensed CC BY 4.0 —
75
+ see [`spec/airs/LICENSE`](../../spec/airs/LICENSE).
@@ -0,0 +1,57 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "tenxyte-mcp-server"
7
+ version = "0.1.0"
8
+ description = "MCP server exposing AIRS/1.0 Agent Token upkeep (status, heartbeat, usage reporting, pending actions) as tools for MCP clients such as Claude Desktop. Pure HTTP client, no dependency on the tenxyte package."
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ requires-python = ">=3.10"
12
+ authors = [{ name = "Tenxyte" }]
13
+ keywords = ["mcp", "model-context-protocol", "ai-agents", "airs", "agent-identity", "claude-desktop"]
14
+ classifiers = [
15
+ "Development Status :: 4 - Beta",
16
+ "Intended Audience :: Developers",
17
+ "License :: OSI Approved :: MIT License",
18
+ "Operating System :: OS Independent",
19
+ "Programming Language :: Python :: 3",
20
+ "Programming Language :: Python :: 3.10",
21
+ "Programming Language :: Python :: 3.11",
22
+ "Programming Language :: Python :: 3.12",
23
+ "Programming Language :: Python :: 3.13",
24
+ "Topic :: Security",
25
+ ]
26
+ dependencies = [
27
+ "mcp>=2.0",
28
+ "httpx>=0.27",
29
+ ]
30
+
31
+ [project.scripts]
32
+ tenxyte-mcp-server = "tenxyte_mcp_server.server:main"
33
+
34
+ [project.optional-dependencies]
35
+ dev = [
36
+ "pytest>=8.0",
37
+ "pytest-asyncio>=0.24",
38
+ "respx>=0.21",
39
+ "hypothesis>=6.0",
40
+ "ruff==0.16.7",
41
+ "black==26.5.1",
42
+ ]
43
+
44
+ [project.urls]
45
+ Homepage = "https://github.com/tenxyte/tenxyte"
46
+ Specification = "https://github.com/tenxyte/tenxyte/blob/main/spec/airs/AIRS-1.0.md"
47
+ Documentation = "https://github.com/tenxyte/tenxyte/tree/main/integrations/mcp-server"
48
+
49
+ [tool.hatch.build.targets.wheel]
50
+ packages = ["src/tenxyte_mcp_server"]
51
+
52
+ [tool.ruff]
53
+ line-length = 120
54
+ extend-exclude = ["tests"]
55
+
56
+ [tool.black]
57
+ line-length = 120
@@ -0,0 +1,3 @@
1
+ [pytest]
2
+ addopts = -q
3
+ asyncio_mode = auto
@@ -0,0 +1,22 @@
1
+ """
2
+ tenxyte-mcp-server — MCP server exposing AIRS/1.0 Agent Token upkeep (spec/airs/AIRS-1.0.md) as
3
+ tools for MCP clients (Claude Desktop, and any other MCP-compatible agent host).
4
+
5
+ A pure HTTP client: never imports the `tenxyte` package (HTTP_Only_Rule). Never holds a human
6
+ JWT and never creates tokens or confirms/denies HITL actions (No_Privilege_Amplification_Rule,
7
+ design.md D3) — see `server.py` for the exact tool surface.
8
+ """
9
+
10
+ from .airs_client import AIRSClient, AIRSError
11
+ from .config import ConfigError, MCPConfig, load_config, load_config_or_exit
12
+
13
+ __version__ = "0.1.0"
14
+
15
+ __all__ = [
16
+ "AIRSClient",
17
+ "AIRSError",
18
+ "ConfigError",
19
+ "MCPConfig",
20
+ "load_config",
21
+ "load_config_or_exit",
22
+ ]
@@ -0,0 +1,114 @@
1
+ """
2
+ Minimal AIRS/1.0 HTTP client for tenxyte-mcp-server.
3
+
4
+ Deliberately self-contained — this package does not depend on `tenxyte-langchain` (design.md:
5
+ "réutilise le protocole, pas le package LC"), so the two connectors stay independently
6
+ installable and versioned. Complies with the HTTP_Only_Rule: never imports `tenxyte`.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from typing import Any
12
+
13
+ import httpx
14
+
15
+ _DEFAULT_DISCOVERY_PATH = "/ai/.well-known/airs/"
16
+
17
+
18
+ class AIRSError(Exception):
19
+ """Raised for any non-2xx AIRS response. `code`/`reason` mirror the server's own fields
20
+ when present (spec/airs/AIRS-1.0.md §8) — not guaranteed to be non-None."""
21
+
22
+ def __init__(
23
+ self, message: str, *, code: str | None = None, reason: str | None = None, status_code: int | None = None
24
+ ):
25
+ super().__init__(message)
26
+ self.code = code
27
+ self.reason = reason
28
+ self.status_code = status_code
29
+
30
+ def as_dict(self) -> dict[str, Any]:
31
+ return {"error": str(self), "code": self.code, "reason": self.reason, "status_code": self.status_code}
32
+
33
+
34
+ class AIRSClient:
35
+ def __init__(
36
+ self,
37
+ base_url: str,
38
+ agent_token: str,
39
+ *,
40
+ access_key: str | None = None,
41
+ access_secret: str | None = None,
42
+ discovery_path: str = _DEFAULT_DISCOVERY_PATH,
43
+ timeout: float = 10.0,
44
+ transport: httpx.BaseTransport | None = None,
45
+ ):
46
+ self.base_url = base_url.rstrip("/")
47
+ self.agent_token = agent_token
48
+ self._discovery_path = discovery_path
49
+ self._discovery: dict[str, Any] | None = None
50
+
51
+ headers = {"Authorization": f"AgentBearer {agent_token}"}
52
+ if access_key:
53
+ headers["X-Access-Key"] = access_key
54
+ if access_secret:
55
+ headers["X-Access-Secret"] = access_secret
56
+
57
+ self._http = httpx.Client(base_url=self.base_url, headers=headers, timeout=timeout, transport=transport)
58
+
59
+ @property
60
+ def discovery(self) -> dict[str, Any]:
61
+ if self._discovery is None:
62
+ response = self._http.get(self._discovery_path)
63
+ if response.status_code != 200:
64
+ raise AIRSError(f"AIRS discovery returned {response.status_code}", status_code=response.status_code)
65
+ self._discovery = response.json()
66
+ return self._discovery
67
+
68
+ def endpoint(self, name: str, **params: Any) -> str:
69
+ template = self.discovery["endpoints"][name]
70
+ return template.format(**{k: str(v) for k, v in params.items()}) if params else template
71
+
72
+ def require_level(self, level: str) -> None:
73
+ if level not in self.discovery.get("conformance", []):
74
+ raise AIRSError(f"Server does not announce AIRS level '{level}'", code="CAPABILITY_MISSING")
75
+
76
+ def _request(self, method: str, path: str, **kwargs: Any) -> httpx.Response:
77
+ response = self._http.request(method, path, **kwargs)
78
+ if 400 <= response.status_code < 600:
79
+ try:
80
+ body = response.json()
81
+ except ValueError:
82
+ body = {"error": response.text}
83
+ message = body.get("error") or body.get("message") or f"AIRS request failed ({response.status_code})"
84
+ code = body.get("code")
85
+ reason = body.get("reason") or body.get("suspended_reason")
86
+ # Tenxyte's report-usage endpoint responds to a budget-exceeded report with
87
+ # {"error": "Budget exceeded", "status": "suspended"} — no "code"/"reason" at all,
88
+ # unlike its other suspension paths. The spec doesn't mandate a code string
89
+ # ([AIRS-CORE-16]), so infer one from the message rather than surfacing a
90
+ # less-useful, entirely blank code/reason for a condition we can actually name.
91
+ if not code and not reason and "budget" in message.lower():
92
+ code = "BUDGET_EXCEEDED"
93
+ raise AIRSError(message, code=code, reason=reason, status_code=response.status_code)
94
+ return response
95
+
96
+ def heartbeat(self, token_id: Any) -> dict[str, Any]:
97
+ return self._request("POST", self.endpoint("heartbeat", id=token_id)).json()
98
+
99
+ def report_usage(
100
+ self, token_id: Any, *, cost_usd: float = 0.0, prompt_tokens: int = 0, completion_tokens: int = 0
101
+ ) -> dict[str, Any]:
102
+ self.require_level("budget")
103
+ return self._request(
104
+ "POST",
105
+ self.endpoint("report_usage", id=token_id),
106
+ json={"cost_usd": cost_usd, "prompt_tokens": prompt_tokens, "completion_tokens": completion_tokens},
107
+ ).json()
108
+
109
+ def pending_actions(self) -> list[dict[str, Any]]:
110
+ self.require_level("hitl")
111
+ return self._request("GET", self.endpoint("pending_actions")).json()
112
+
113
+ def close(self) -> None:
114
+ self._http.close()
@@ -0,0 +1,68 @@
1
+ """
2
+ Environment-variable configuration for tenxyte-mcp-server (spec z_aud_2, Requirement 5.2).
3
+
4
+ Configured exclusively through environment variables — never a config file, never a CLI flag
5
+ carrying secrets. Missing required variables fail loudly at startup (stderr + non-zero exit),
6
+ never a degraded/partial start (design.md: "Démarrage : variables d'env manquantes → message
7
+ d'erreur explicite sur stderr + exit != 0").
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import os
13
+ import sys
14
+ from dataclasses import dataclass
15
+
16
+ REQUIRED_VARS = ("TENXYTE_BASE_URL", "TENXYTE_AGENT_TOKEN")
17
+ OPTIONAL_VARS = ("TENXYTE_ACCESS_KEY", "TENXYTE_ACCESS_SECRET")
18
+
19
+
20
+ class ConfigError(Exception):
21
+ pass
22
+
23
+
24
+ @dataclass(frozen=True)
25
+ class MCPConfig:
26
+ base_url: str
27
+ agent_token: str
28
+ access_key: str | None = None
29
+ access_secret: str | None = None
30
+
31
+
32
+ def load_config(env: dict[str, str] | None = None) -> MCPConfig:
33
+ """
34
+ Read and validate configuration from the environment.
35
+
36
+ `TENXYTE_BASE_URL` and `TENXYTE_AGENT_TOKEN` are required — the No_Privilege_Amplification_Rule
37
+ (design.md D3) means this server never holds anything more privileged than one already-issued
38
+ Agent Token, so there is no "create a token" fallback to fall back to. `TENXYTE_ACCESS_KEY` /
39
+ `TENXYTE_ACCESS_SECRET` are optional (only needed if the target requires application
40
+ credentials).
41
+ """
42
+ env = os.environ if env is None else env
43
+
44
+ missing = [name for name in REQUIRED_VARS if not env.get(name)]
45
+ if missing:
46
+ raise ConfigError(
47
+ "Missing required environment variable(s): "
48
+ + ", ".join(missing)
49
+ + ". tenxyte-mcp-server needs TENXYTE_BASE_URL and TENXYTE_AGENT_TOKEN to start; "
50
+ + "TENXYTE_ACCESS_KEY / TENXYTE_ACCESS_SECRET are optional. See README.md."
51
+ )
52
+
53
+ return MCPConfig(
54
+ base_url=env["TENXYTE_BASE_URL"].rstrip("/"),
55
+ agent_token=env["TENXYTE_AGENT_TOKEN"],
56
+ access_key=env.get("TENXYTE_ACCESS_KEY"),
57
+ access_secret=env.get("TENXYTE_ACCESS_SECRET"),
58
+ )
59
+
60
+
61
+ def load_config_or_exit(env: dict[str, str] | None = None) -> MCPConfig:
62
+ """Same as `load_config`, but prints to stderr and calls `sys.exit(2)` on failure — the
63
+ entry point CLI should use this, tests should use `load_config` directly."""
64
+ try:
65
+ return load_config(env)
66
+ except ConfigError as exc:
67
+ print(f"tenxyte-mcp-server: {exc}", file=sys.stderr)
68
+ sys.exit(2)
@@ -0,0 +1,172 @@
1
+ """
2
+ tenxyte-mcp-server — MCP server exposing AIRS Agent Token upkeep as tools (spec z_aud_2,
3
+ Requirement 5).
4
+
5
+ Surface is deliberately asymmetric (design.md "Décision de conception : MCP sans amplification
6
+ de privilèges" / No_Privilege_Amplification_Rule, D3): everything here is upkeep an *agent* may
7
+ legitimately do to its own already-issued token (check status, heartbeat, report usage, see its
8
+ own pending actions, introspect the server). Nothing here creates a token, confirms or denies a
9
+ HITL action, or accepts a human credential — those stay strictly on the human side of Tenxyte's
10
+ own API, never in reach of this process.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import functools
16
+ import json
17
+ from collections.abc import Callable
18
+ from typing import Any, TypeVar
19
+
20
+ from mcp.server.mcpserver import MCPServer
21
+
22
+ from .airs_client import AIRSClient, AIRSError
23
+ from .config import MCPConfig, load_config_or_exit
24
+
25
+ mcp = MCPServer("tenxyte-airs")
26
+
27
+ _client: AIRSClient | None = None
28
+ _token_id: Any = None
29
+
30
+ _F = TypeVar("_F", bound=Callable[..., Any])
31
+
32
+
33
+ def _get_client() -> AIRSClient:
34
+ if _client is None:
35
+ raise RuntimeError("tenxyte-mcp-server is not configured (call configure() first)")
36
+ return _client
37
+
38
+
39
+ def configure(config: MCPConfig, *, token_id: Any = None) -> None:
40
+ """
41
+ Wire this module's global client from a loaded `MCPConfig`.
42
+
43
+ `token_id` is the numeric/string id AIRS assigned this Agent Token at issuance (distinct
44
+ from the raw token value); several endpoints are addressed by id, not by the raw token.
45
+ When not supplied, the tools that need it (`airs_heartbeat`, `airs_report_usage`) will report
46
+ a structured error asking for `TENXYTE_AGENT_TOKEN_ID` to be set instead of crashing.
47
+ """
48
+ global _client, _token_id
49
+ _client = AIRSClient(
50
+ config.base_url,
51
+ config.agent_token,
52
+ access_key=config.access_key,
53
+ access_secret=config.access_secret,
54
+ )
55
+ _token_id = token_id
56
+
57
+
58
+ class MissingTokenIdError(AIRSError):
59
+ def __init__(self):
60
+ super().__init__("TENXYTE_AGENT_TOKEN_ID is not set", code="MISSING_TOKEN_ID")
61
+
62
+
63
+ def _require_token_id() -> Any:
64
+ if _token_id is None:
65
+ raise MissingTokenIdError
66
+ return _token_id
67
+
68
+
69
+ def _structured_errors(fn: _F) -> _F:
70
+ """
71
+ Every tool below is wrapped with this: whatever goes wrong (a typed `AIRSError` from the
72
+ client, or anything else — a transport failure, a bug), the tool raises a JSON-shaped
73
+ `RuntimeError` rather than letting a bare, unstructured exception surface. The MCP framework
74
+ itself already guarantees the *process* survives an exception raised from inside a tool
75
+ ([AIRS-CORE-16], Requirement 5.5) — this decorator is what guarantees the *error content* is
76
+ always structured, not just "the process didn't crash".
77
+ """
78
+
79
+ @functools.wraps(fn)
80
+ def wrapper(*args: Any, **kwargs: Any) -> Any:
81
+ try:
82
+ return fn(*args, **kwargs)
83
+ except AIRSError as exc:
84
+ raise RuntimeError(json.dumps(exc.as_dict())) from exc
85
+ except Exception as exc:
86
+ raise RuntimeError(json.dumps({"error": str(exc), "code": "UNEXPECTED_ERROR"})) from exc
87
+
88
+ return wrapper # type: ignore[return-value]
89
+
90
+
91
+ @mcp.tool()
92
+ @_structured_errors
93
+ def airs_discovery() -> dict[str, Any]:
94
+ """Return the target server's AIRS discovery document (spec version, active Conformance
95
+ Levels, endpoint map, limits) — capabilities only, no data ([AIRS-DISC-1])."""
96
+ return _get_client().discovery
97
+
98
+
99
+ @mcp.tool()
100
+ @_structured_errors
101
+ def airs_token_status() -> dict[str, Any]:
102
+ """
103
+ Report whether this Agent Token is still usable.
104
+
105
+ There is no dedicated agent-side "status" endpoint in AIRS/1.0 — this sends a heartbeat and
106
+ reports success/failure, since that is the one agent-callable operation that reveals a
107
+ token's liveness without any side effect beyond what heartbeats already do. If the token is
108
+ suspended, revoked, or expired, this (like every tool) raises a structured error rather than
109
+ reporting a fake "ok" status (Requirement 5.5).
110
+ """
111
+ client = _get_client()
112
+ token_id = _require_token_id()
113
+ result = client.heartbeat(token_id)
114
+ return {"status": "ACTIVE", **result}
115
+
116
+
117
+ @mcp.tool()
118
+ @_structured_errors
119
+ def airs_heartbeat() -> dict[str, Any]:
120
+ """Send a liveness heartbeat, maintaining the Dead Man's Switch Guardrail ([AIRS-GUARDS-3])."""
121
+ return _get_client().heartbeat(_require_token_id())
122
+
123
+
124
+ @mcp.tool()
125
+ @_structured_errors
126
+ def airs_report_usage(cost_usd: float, prompt_tokens: int = 0, completion_tokens: int = 0) -> dict[str, Any]:
127
+ """Report incremental LLM usage/cost against this token's budget ([AIRS-BUDGET-1]). Raises a
128
+ structured error if this report pushes the token over its limit (BUDGET_EXCEEDED)."""
129
+ return _get_client().report_usage(
130
+ _require_token_id(), cost_usd=cost_usd, prompt_tokens=prompt_tokens, completion_tokens=completion_tokens
131
+ )
132
+
133
+
134
+ @mcp.tool()
135
+ @_structured_errors
136
+ def airs_list_pending_actions() -> list[dict[str, Any]]:
137
+ """
138
+ List outstanding HITL Pending Actions.
139
+
140
+ Note: Tenxyte's reference implementation currently scopes this listing to the Delegating
141
+ User's own human authentication, not the Agent Token — calling this tool against Tenxyte
142
+ will surface that as a structured PERMISSION error, not a crash. It is included for
143
+ AIRS/1.0 implementations that do expose it to the agent side.
144
+ """
145
+ return _get_client().pending_actions()
146
+
147
+
148
+ @mcp.resource("airs://token/status")
149
+ def token_status_resource() -> dict[str, Any]:
150
+ """Read-only resource mirroring `airs_token_status` (already wraps its own errors)."""
151
+ return airs_token_status()
152
+
153
+
154
+ @mcp.resource("airs://budget")
155
+ @_structured_errors
156
+ def budget_resource() -> dict[str, Any]:
157
+ """Read-only resource: the discovery document's `budget`-relevant limits, if any."""
158
+ discovery = _get_client().discovery
159
+ return {"conformance": discovery.get("conformance", []), "limits": discovery.get("limits", {})}
160
+
161
+
162
+ def main() -> None:
163
+ import os
164
+
165
+ config = load_config_or_exit()
166
+ token_id = os.environ.get("TENXYTE_AGENT_TOKEN_ID")
167
+ configure(config, token_id=token_id)
168
+ mcp.run(transport="stdio")
169
+
170
+
171
+ if __name__ == "__main__":
172
+ main()
File without changes
@@ -0,0 +1,23 @@
1
+ import pytest
2
+
3
+ from tenxyte_mcp_server import server
4
+ from tenxyte_mcp_server.config import MCPConfig
5
+
6
+ DISCOVERY_BODY = {
7
+ "airs_version": "1.0",
8
+ "conformance": ["core", "hitl", "guards", "budget", "trace"],
9
+ "endpoints": {
10
+ "heartbeat": "/ai/tokens/{id}/heartbeat/",
11
+ "report_usage": "/ai/tokens/{id}/report-usage/",
12
+ "pending_actions": "/ai/pending-actions/",
13
+ },
14
+ "limits": {"token_max_lifetime": 86400, "default_expiry": 3600},
15
+ }
16
+
17
+
18
+ @pytest.fixture(autouse=True)
19
+ def _configured_server():
20
+ server.configure(MCPConfig(base_url="https://airs.test", agent_token="raw-token"), token_id=1)
21
+ yield
22
+ server._client = None
23
+ server._token_id = None
@@ -0,0 +1,45 @@
1
+ import pytest
2
+
3
+ from tenxyte_mcp_server.config import ConfigError, load_config
4
+
5
+
6
+ def test_loads_with_required_vars_only():
7
+ config = load_config({"TENXYTE_BASE_URL": "https://x.test/", "TENXYTE_AGENT_TOKEN": "raw"})
8
+ assert config.base_url == "https://x.test" # trailing slash stripped
9
+ assert config.agent_token == "raw"
10
+ assert config.access_key is None
11
+ assert config.access_secret is None
12
+
13
+
14
+ def test_loads_with_all_vars():
15
+ config = load_config(
16
+ {
17
+ "TENXYTE_BASE_URL": "https://x.test",
18
+ "TENXYTE_AGENT_TOKEN": "raw",
19
+ "TENXYTE_ACCESS_KEY": "key",
20
+ "TENXYTE_ACCESS_SECRET": "secret",
21
+ }
22
+ )
23
+ assert config.access_key == "key"
24
+ assert config.access_secret == "secret"
25
+
26
+
27
+ @pytest.mark.parametrize(
28
+ "env",
29
+ [
30
+ {},
31
+ {"TENXYTE_BASE_URL": "https://x.test"},
32
+ {"TENXYTE_AGENT_TOKEN": "raw"},
33
+ ],
34
+ )
35
+ def test_missing_required_vars_raises(env):
36
+ with pytest.raises(ConfigError):
37
+ load_config(env)
38
+
39
+
40
+ def test_error_message_names_every_missing_var():
41
+ with pytest.raises(ConfigError) as exc_info:
42
+ load_config({})
43
+ message = str(exc_info.value)
44
+ assert "TENXYTE_BASE_URL" in message
45
+ assert "TENXYTE_AGENT_TOKEN" in message
@@ -0,0 +1,57 @@
1
+ """
2
+ Feature: z_aud_2, Property 11 (volet MCP): Étanchéité HTTP des intégrations
3
+
4
+ Validates: Requirements 5.2, 9.3
5
+ """
6
+
7
+ import ast
8
+ import importlib
9
+ import pathlib
10
+ import sys
11
+
12
+ import tenxyte_mcp_server
13
+
14
+ PACKAGE_ROOT = pathlib.Path(tenxyte_mcp_server.__file__).parent
15
+
16
+
17
+ def _imported_top_level_names(source_path: pathlib.Path) -> set[str]:
18
+ tree = ast.parse(source_path.read_text(encoding="utf-8"), filename=str(source_path))
19
+ names = set()
20
+ for node in ast.walk(tree):
21
+ if isinstance(node, ast.Import):
22
+ for alias in node.names:
23
+ names.add(alias.name.split(".")[0])
24
+ elif isinstance(node, ast.ImportFrom) and node.module and node.level == 0:
25
+ names.add(node.module.split(".")[0])
26
+ return names
27
+
28
+
29
+ def test_no_source_file_imports_tenxyte():
30
+ offenders = {}
31
+ for py_file in PACKAGE_ROOT.rglob("*.py"):
32
+ imported = _imported_top_level_names(py_file)
33
+ if "tenxyte" in imported:
34
+ offenders[str(py_file)] = imported
35
+ assert not offenders, f"tenxyte_mcp_server must never import 'tenxyte': {offenders}"
36
+
37
+
38
+ def test_no_tenxyte_module_in_sys_modules_after_import():
39
+ importlib.reload(tenxyte_mcp_server)
40
+ assert not any(name == "tenxyte" or name.startswith("tenxyte.") for name in sys.modules)
41
+
42
+
43
+ def test_does_not_depend_on_tenxyte_langchain():
44
+ """The two connectors are independent packages — neither depends on the other."""
45
+ offenders = {}
46
+ for py_file in PACKAGE_ROOT.rglob("*.py"):
47
+ imported = _imported_top_level_names(py_file)
48
+ if "tenxyte_langchain" in imported:
49
+ offenders[str(py_file)] = imported
50
+ assert not offenders, f"tenxyte_mcp_server must not depend on tenxyte_langchain: {offenders}"
51
+
52
+
53
+ def test_declared_dependencies_exclude_tenxyte():
54
+ pyproject = pathlib.Path(__file__).resolve().parent.parent / "pyproject.toml"
55
+ content = pyproject.read_text(encoding="utf-8")
56
+ assert '"tenxyte"' not in content
57
+ assert "tenxyte-langchain" not in content
@@ -0,0 +1,115 @@
1
+ """
2
+ Feature: z_aud_2, Property 9 (volet MCP): chaque état terminal produit une erreur MCP structurée,
3
+ process vivant.
4
+
5
+ Validates: Requirements 5.5
6
+ """
7
+
8
+ import json
9
+ from contextlib import contextmanager
10
+
11
+ import httpx
12
+ import pytest
13
+ import respx
14
+ from hypothesis import given
15
+ from hypothesis import strategies as st
16
+ from mcp.server.mcpserver.exceptions import UnexpectedToolError
17
+
18
+ from tenxyte_mcp_server import server
19
+
20
+ from .conftest import DISCOVERY_BODY
21
+
22
+ _SUSPENSION_REASONS = ["RATE_LIMIT", "ANOMALY", "MANUAL", "HEARTBEAT_MISSING", "BUDGET_EXCEEDED"]
23
+
24
+
25
+ def _structured_cause(exc: BaseException) -> dict:
26
+ assert exc.__cause__ is not None, "expected a structured cause carrying the JSON payload"
27
+ return json.loads(str(exc.__cause__))
28
+
29
+
30
+ @contextmanager
31
+ def _mocked(heartbeat_response):
32
+ with respx.mock(assert_all_called=False) as router:
33
+ router.get("https://airs.test/ai/.well-known/airs/").respond(200, json=DISCOVERY_BODY)
34
+ router.post("https://airs.test/ai/tokens/1/heartbeat/").mock(side_effect=heartbeat_response)
35
+ yield router
36
+
37
+
38
+ @pytest.mark.asyncio
39
+ @given(reason=st.sampled_from(_SUSPENSION_REASONS))
40
+ async def test_property_9_every_terminal_reason_yields_structured_error_process_survives(reason):
41
+ def _respond(request):
42
+ return httpx.Response(
43
+ 403, json={"error": "suspended", "code": "AGENT_TOKEN_STATUS_SUSPENDED", "reason": reason}
44
+ )
45
+
46
+ with _mocked(_respond):
47
+ with pytest.raises(UnexpectedToolError) as exc_info:
48
+ await server.mcp.call_tool("airs_heartbeat", {})
49
+
50
+ payload = _structured_cause(exc_info.value)
51
+ assert payload["reason"] == reason
52
+ assert payload["code"] == "AGENT_TOKEN_STATUS_SUSPENDED"
53
+
54
+ # The process is manifestly still alive: a second, independent call still goes through the
55
+ # framework normally rather than the whole server having gone down.
56
+ with _mocked(lambda request: httpx.Response(200, json={"status": "ok"})):
57
+ result = await server.mcp.call_tool("airs_heartbeat", {})
58
+ assert result is not None
59
+
60
+
61
+ @pytest.mark.asyncio
62
+ async def test_budget_exceeded_inferred_even_without_code_or_reason():
63
+ """Regression: Tenxyte's real report-usage endpoint returns {"error": "Budget exceeded",
64
+ "status": "suspended"} with NO "code"/"reason" field — caught while running the CrewAI
65
+ example end-to-end, where this used to surface as a blank code/reason."""
66
+ with respx.mock(assert_all_called=False) as router:
67
+ router.get("https://airs.test/ai/.well-known/airs/").respond(200, json=DISCOVERY_BODY)
68
+ router.post("https://airs.test/ai/tokens/1/report-usage/").respond(
69
+ 403, json={"error": "Budget exceeded", "status": "suspended"}
70
+ )
71
+ with pytest.raises(UnexpectedToolError) as exc_info:
72
+ await server.mcp.call_tool("airs_report_usage", {"cost_usd": 1.0})
73
+ payload = _structured_cause(exc_info.value)
74
+ assert payload["code"] == "BUDGET_EXCEEDED"
75
+
76
+
77
+ @pytest.mark.asyncio
78
+ async def test_property_9_revoked_yields_structured_error():
79
+ with _mocked(lambda request: httpx.Response(403, json={"error": "revoked", "code": "AGENT_TOKEN_STATUS_REVOKED"})):
80
+ with pytest.raises(UnexpectedToolError) as exc_info:
81
+ await server.mcp.call_tool("airs_heartbeat", {})
82
+ payload = _structured_cause(exc_info.value)
83
+ assert payload["code"] == "AGENT_TOKEN_STATUS_REVOKED"
84
+
85
+
86
+ @pytest.mark.asyncio
87
+ async def test_property_9_expired_yields_structured_error():
88
+ with _mocked(lambda request: httpx.Response(403, json={"error": "expired", "code": "AGENT_TOKEN_EXPIRED"})):
89
+ with pytest.raises(UnexpectedToolError) as exc_info:
90
+ await server.mcp.call_tool("airs_heartbeat", {})
91
+ payload = _structured_cause(exc_info.value)
92
+ assert payload["code"] == "AGENT_TOKEN_EXPIRED"
93
+
94
+
95
+ @pytest.mark.asyncio
96
+ async def test_property_9_transport_failure_also_structured_not_a_bare_crash():
97
+ """Even a non-AIRS failure (network error) is turned into a structured, JSON-shaped cause."""
98
+
99
+ def _raise(request):
100
+ raise httpx.ConnectError("refused")
101
+
102
+ with _mocked(_raise):
103
+ with pytest.raises(UnexpectedToolError) as exc_info:
104
+ await server.mcp.call_tool("airs_heartbeat", {})
105
+ payload = _structured_cause(exc_info.value)
106
+ assert payload["code"] == "UNEXPECTED_ERROR"
107
+
108
+
109
+ @pytest.mark.asyncio
110
+ async def test_property_9_missing_token_id_is_structured_not_a_crash():
111
+ server._token_id = None
112
+ with pytest.raises(UnexpectedToolError) as exc_info:
113
+ await server.mcp.call_tool("airs_heartbeat", {})
114
+ payload = _structured_cause(exc_info.value)
115
+ assert payload["code"] == "MISSING_TOKEN_ID"
@@ -0,0 +1,60 @@
1
+ """
2
+ Feature: z_aud_2, Property 10: Surface MCP sans amplification de privilèges
3
+
4
+ Validates: Requirements 5.3, 5.4
5
+ """
6
+
7
+ import inspect
8
+
9
+ import pytest
10
+
11
+ from tenxyte_mcp_server import server
12
+
13
+ _EXPECTED_TOOLS = {
14
+ "airs_token_status",
15
+ "airs_heartbeat",
16
+ "airs_report_usage",
17
+ "airs_list_pending_actions",
18
+ "airs_discovery",
19
+ }
20
+
21
+ _FORBIDDEN_SUBSTRINGS = ("create", "confirm", "deny", "revoke", "issue")
22
+
23
+
24
+ @pytest.mark.asyncio
25
+ async def test_exact_tool_set():
26
+ tools = await server.mcp.list_tools()
27
+ names = {t.name for t in tools}
28
+ assert names == _EXPECTED_TOOLS
29
+
30
+
31
+ @pytest.mark.asyncio
32
+ async def test_no_privilege_amplifying_tool_names():
33
+ tools = await server.mcp.list_tools()
34
+ for tool in tools:
35
+ lowered = tool.name.lower()
36
+ for forbidden in _FORBIDDEN_SUBSTRINGS:
37
+ assert forbidden not in lowered, f"tool {tool.name!r} looks privilege-amplifying ({forbidden!r})"
38
+
39
+
40
+ def test_no_configuration_option_accepts_a_user_jwt():
41
+ """Neither MCPConfig nor AIRSClient exposes any field/parameter for a human JWT."""
42
+ from tenxyte_mcp_server.airs_client import AIRSClient
43
+ from tenxyte_mcp_server.config import MCPConfig
44
+
45
+ for target in (MCPConfig, AIRSClient.__init__):
46
+ signature = inspect.signature(target)
47
+ for name in signature.parameters:
48
+ assert "jwt" not in name.lower(), f"{target} accepts a JWT-shaped parameter: {name}"
49
+
50
+
51
+ def test_no_source_file_creates_agent_tokens_or_confirms_hitl():
52
+ import pathlib
53
+
54
+ package_root = pathlib.Path(server.__file__).parent
55
+ forbidden_endpoint_fragments = ['tokens/", method="POST', "pending_action_confirm", "pending_action_deny"]
56
+
57
+ for py_file in package_root.rglob("*.py"):
58
+ content = py_file.read_text(encoding="utf-8")
59
+ for fragment in forbidden_endpoint_fragments:
60
+ assert fragment not in content, f"{py_file} references a human-authority operation: {fragment!r}"