From 5bf15d0cc6d052c87290037d30cfd2c96ba69476 Mon Sep 17 00:00:00 2001 From: tercel Date: Fri, 27 Nov 2026 16:30:49 +0800 Subject: [PATCH 1/9] refactor(mcp): own Python tool schema projection Signed-off-by: tercel --- mcp/python/src/apcore_mcp/adapters/schema.py | 81 ++++++++++--------- .../src/apcore_mcp/converters/openai.py | 8 +- mcp/python/src/apcore_mcp/server/factory.py | 25 +----- mcp/python/tests/converters/test_openai.py | 14 ++-- 4 files changed, 53 insertions(+), 75 deletions(-) diff --git a/mcp/python/src/apcore_mcp/adapters/schema.py b/mcp/python/src/apcore_mcp/adapters/schema.py index b0051526..fb91b91e 100644 --- a/mcp/python/src/apcore_mcp/adapters/schema.py +++ b/mcp/python/src/apcore_mcp/adapters/schema.py @@ -3,6 +3,7 @@ from __future__ import annotations import copy +from collections.abc import Iterator from typing import Any _MAX_REF_DEPTH = 32 @@ -16,6 +17,38 @@ _SCHEMA_CHILD_SCHEMA_KEYS = ("items", "not", "if", "then", "else", "contains", "propertyNames") +def _schema_nodes(node: Any) -> Iterator[dict[str, Any]]: + if not isinstance(node, dict): + return + yield node + for key in _SCHEMA_CHILD_DICT_KEYS: + children = node.get(key) + if isinstance(children, dict): + for child in children.values(): + yield from _schema_nodes(child) + for key in _SCHEMA_CHILD_LIST_KEYS: + children = node.get(key) + if isinstance(children, list): + for child in children: + yield from _schema_nodes(child) + for key in _SCHEMA_CHILD_SCHEMA_KEYS: + child = node.get(key) + if isinstance(child, list): + for item in child: # Legacy tuple validation can use schema arrays. + yield from _schema_nodes(item) + else: + yield from _schema_nodes(child) + yield from _schema_nodes(node.get("additionalProperties")) + + +def apply_llm_descriptions(schema: dict[str, Any]) -> None: + """Use LLM descriptions on schema nodes before removing extensions.""" + for node in _schema_nodes(schema): + description = node.get("x-llm-description") + if isinstance(description, str): + node["description"] = description + + class SchemaConverter: """Converts apcore ModuleDescriptor schemas to MCP-compatible schemas. @@ -112,46 +145,14 @@ def _inject_additional_properties_false(self, node: Any) -> None: NOT descend into literal-data keys like ``enum``, ``const``, ``examples``, ``default``, ``required``. """ - if not isinstance(node, dict): - return - - node_type = node.get("type") - type_is_object = node_type == "object" or (isinstance(node_type, list) and "object" in node_type) - # Treat schema as object-like when it has "properties" and no - # conflicting non-object scalar type. - has_properties = "properties" in node - non_object_scalar = isinstance(node_type, str) and node_type != "object" - is_object = type_is_object or (has_properties and not non_object_scalar) - - if is_object and "additionalProperties" not in node: - node["additionalProperties"] = False - - # Recurse only into known subschema-bearing keywords. - for key in _SCHEMA_CHILD_DICT_KEYS: - child = node.get(key) - if isinstance(child, dict): - for sub in child.values(): - self._inject_additional_properties_false(sub) - - for key in _SCHEMA_CHILD_LIST_KEYS: - child = node.get(key) - if isinstance(child, list): - for item in child: - self._inject_additional_properties_false(item) - - for key in _SCHEMA_CHILD_SCHEMA_KEYS: - child = node.get(key) - if isinstance(child, dict): - self._inject_additional_properties_false(child) - elif isinstance(child, list): - # ``items`` may be a list of schemas (legacy tuple validation) - for item in child: - self._inject_additional_properties_false(item) - - # additionalProperties itself may be a schema dict. - ap = node.get("additionalProperties") - if isinstance(ap, dict): - self._inject_additional_properties_false(ap) + for schema in _schema_nodes(node): + node_type = schema.get("type") + type_is_object = node_type == "object" or (isinstance(node_type, list) and "object" in node_type) + # A properties map implies an object unless a scalar type says otherwise. + non_object_scalar = isinstance(node_type, str) and node_type != "object" + is_object = type_is_object or ("properties" in schema and not non_object_scalar) + if is_object and "additionalProperties" not in schema: + schema["additionalProperties"] = False def _inline_refs( self, diff --git a/mcp/python/src/apcore_mcp/converters/openai.py b/mcp/python/src/apcore_mcp/converters/openai.py index 1e61321d..1a6db5f5 100644 --- a/mcp/python/src/apcore_mcp/converters/openai.py +++ b/mcp/python/src/apcore_mcp/converters/openai.py @@ -5,12 +5,12 @@ import logging from typing import Any -from apcore.schema.strict import _apply_llm_descriptions, to_strict_schema +from apcore.schema.strict import to_strict_schema import apcore_mcp.markdown as _markdown from apcore_mcp.adapters.annotations import AnnotationMapper from apcore_mcp.adapters.id_normalizer import ModuleIDNormalizer -from apcore_mcp.adapters.schema import SchemaConverter +from apcore_mcp.adapters.schema import SchemaConverter, apply_llm_descriptions _logger = logging.getLogger(__name__) @@ -198,8 +198,6 @@ def _apply_strict_mode(self, schema: dict[str, Any]) -> dict[str, Any]: 6. Optional properties become nullable 7. Recurses into nested objects, array items, oneOf/anyOf/allOf, and $defs - This matches the behavior of SchemaExporter.export_openai(). - Args: schema: JSON Schema dict to transform. @@ -209,5 +207,5 @@ def _apply_strict_mode(self, schema: dict[str, Any]) -> dict[str, Any]: import copy schema = copy.deepcopy(schema) - _apply_llm_descriptions(schema) + apply_llm_descriptions(schema) return to_strict_schema(schema) diff --git a/mcp/python/src/apcore_mcp/server/factory.py b/mcp/python/src/apcore_mcp/server/factory.py index 843c6510..81f720e7 100644 --- a/mcp/python/src/apcore_mcp/server/factory.py +++ b/mcp/python/src/apcore_mcp/server/factory.py @@ -16,8 +16,6 @@ import jsonschema # type: ignore[import-untyped] # MCP supplies jsonschema without its optional typing stubs. from apcore import CancelToken, Identity, ModuleError from apcore import Registry as CoreRegistry -from apcore.schema.exporter import SchemaExporter -from apcore.schema.types import SchemaDefinition from mcp import types as mcp_types from mcp.server.lowlevel import NotificationOptions, Server from mcp.server.lowlevel.helper_types import ReadResourceContents @@ -275,7 +273,6 @@ def __init__(self, *, strict: bool = True, rich_description: bool = False) -> No # the TS factory's `_warnedToolkitMissing` guard). self._warned_toolkit_missing = False self._annotation_mapper = AnnotationMapper() - self._schema_exporter = SchemaExporter() from apcore_mcp.adapters.errors import ErrorMapper self._error_mapper = ErrorMapper() @@ -328,8 +325,8 @@ def build_tool( - descriptor.module_id -> Tool.name - descriptor.description -> Tool.description - descriptor.input_schema -> independent MCP Tool.inputSchema copy - - SchemaExporter.export_mcp() -> ToolAnnotations hints (camelCase) - - AnnotationMapper -> requires_approval, streaming (_meta), title + - AnnotationMapper -> ToolAnnotations hints and requires_approval metadata + - descriptor.annotations.streaming -> streaming metadata Args: descriptor: ModuleDescriptor with module_id, description, @@ -363,24 +360,8 @@ def build_tool( raise ValueError("MCP input schema must allow an object root") input_schema["type"] = "object" - # NOTE: Python uses SchemaExporter.export_mcp() for annotation mapping, - # while TypeScript uses AnnotationMapper.toMcpAnnotations() directly. - # Both produce identical output. If annotation logic changes, update both paths. - schema_def = SchemaDefinition( - module_id=descriptor.module_id, - description=descriptor.description, - input_schema=descriptor.input_schema, - output_schema=getattr(descriptor, "output_schema", {}), - ) - exported = self._schema_exporter.export_mcp(schema_def, annotations=descriptor.annotations) - hints = exported["annotations"] - tool_annotations = mcp_types.ToolAnnotations( - readOnlyHint=hints.get("readOnlyHint"), - destructiveHint=hints.get("destructiveHint"), - idempotentHint=hints.get("idempotentHint"), - openWorldHint=hints.get("openWorldHint"), - title=None, + **self._annotation_mapper.to_mcp_annotations(descriptor.annotations), ) # Build optional _meta with requires_approval and streaming hints diff --git a/mcp/python/tests/converters/test_openai.py b/mcp/python/tests/converters/test_openai.py index 70fd5933..290c04a5 100644 --- a/mcp/python/tests/converters/test_openai.py +++ b/mcp/python/tests/converters/test_openai.py @@ -568,20 +568,18 @@ def test_strict_mode_strips_x_extensions(self, converter): assert "x-llm-description" not in params["properties"]["name"] assert "x-sensitive" not in params["properties"]["name"] - def test_strict_mode_promotes_x_llm_description(self, converter): + @pytest.mark.parametrize("include_base_description", [True, False]) + def test_strict_mode_promotes_x_llm_description(self, converter, include_base_description): """x-llm-description is promoted to description before stripping.""" + query_schema = {"type": "string", "x-llm-description": "LLM-optimized description"} + if include_base_description: + query_schema["description"] = "Original description" descriptor = ModuleDescriptor( module_id="test.llm_desc", description="Test", input_schema={ "type": "object", - "properties": { - "query": { - "type": "string", - "description": "Original description", - "x-llm-description": "LLM-optimized description", - }, - }, + "properties": {"query": query_schema}, "required": ["query"], }, output_schema={}, From 22c5070b09d4411f5d8fc79c8f3043a73f0c1c36 Mon Sep 17 00:00:00 2001 From: tercel Date: Fri, 27 Nov 2026 16:30:49 +0800 Subject: [PATCH 2/9] refactor(toolkit): exercise Prometheus listeners independently Signed-off-by: tercel --- toolkit/python/README.md | 2 - .../python/tests/test_prometheus_server.py | 38 +++++----------- toolkit/rust/README.md | 4 +- toolkit/rust/tests/prometheus_server.rs | 45 ++++++++----------- toolkit/typescript/README.md | 9 ++-- .../tests/prometheus-server.test.ts | 42 ++++++----------- 6 files changed, 48 insertions(+), 92 deletions(-) diff --git a/toolkit/python/README.md b/toolkit/python/README.md index 4c15c1d4..eb5916d7 100644 --- a/toolkit/python/README.md +++ b/toolkit/python/README.md @@ -113,8 +113,6 @@ with create_prometheus_server( ``` The context closes the listening socket and waits for accepted requests to finish. -With a Core version that exposes `PrometheusExporter.export`, that bound method can -also serve as the rendering callback. ### Scanning and Writing diff --git a/toolkit/python/tests/test_prometheus_server.py b/toolkit/python/tests/test_prometheus_server.py index 97ea48b6..ef0e91de 100644 --- a/toolkit/python/tests/test_prometheus_server.py +++ b/toolkit/python/tests/test_prometheus_server.py @@ -1,4 +1,4 @@ -"""HTTP-level compatibility for the standalone Prometheus listener.""" +"""HTTP-level contract for the standalone Prometheus listener.""" from __future__ import annotations @@ -12,7 +12,6 @@ from typing import Never import pytest -from apcore.observability import MetricsCollector, PrometheusExporter, UsageCollector from apcore_toolkit import create_prometheus_server @@ -39,31 +38,16 @@ def request(port: int, path: str, method: str = "GET") -> tuple[int, dict[str, s client.close() -@pytest.mark.parametrize("populated", [False, True]) -def test_scrape_matches_legacy_http_response(populated: bool) -> None: - metrics = MetricsCollector() - usage = UsageCollector() - if populated: - metrics.increment("example_calls_total", {"site": "课堂"}) - metrics.observe("apcore_module_duration_seconds", {"module_id": "math.add"}, 0.01) - usage.record(module_id="math.add", caller_id="client", latency_ms=10.0, success=True) - exporter = PrometheusExporter(metrics, usage_collector=usage) - exporter.start(port=0, path="/scrape") - try: - assert exporter._server is not None - legacy_status, legacy_headers, legacy_body = request(exporter._server.server_port, "/scrape") - with running(create_prometheus_server(exporter.export, port=0, metrics_path="/scrape")) as port: - status, headers, body = request(port, "/scrape?format=prometheus") - assert status == legacy_status == 200 - assert body == legacy_body == exporter.export().encode("utf-8") - assert ( - headers["Content-Type"] == legacy_headers["Content-Type"] == "text/plain; version=0.0.4; charset=utf-8" - ) - assert headers["Content-Length"] == str(len(body)) - assert request(port, "/metrics")[0] == 404 - assert request(port, "/scrape/")[0] == 404 - finally: - exporter.stop() +@pytest.mark.parametrize("text", ["", '# TYPE example_calls_total counter\nexample_calls_total{site="\u8bfe\u5802"} 1\n']) +def test_scrape_writes_the_supplied_metrics_text(text: str) -> None: + with running(create_prometheus_server(lambda: text, port=0, metrics_path="/scrape")) as port: + status, headers, body = request(port, "/scrape?format=prometheus") + assert status == 200 + assert body == text.encode("utf-8") + assert headers["Content-Type"] == "text/plain; version=0.0.4; charset=utf-8" + assert headers["Content-Length"] == str(len(body)) + assert request(port, "/metrics")[0] == 404 + assert request(port, "/scrape/")[0] == 404 def test_routes_readiness_and_rejects_non_get_requests() -> None: diff --git a/toolkit/rust/README.md b/toolkit/rust/README.md index 37472dd9..72c7f2ab 100644 --- a/toolkit/rust/README.md +++ b/toolkit/rust/README.md @@ -351,9 +351,7 @@ async fn listen_for_scrapes( A GET serves `/metrics` by default, `/healthz` for liveness, and `/readyz` for the supplied readiness callback. Set a different scrape path with `with_metrics_path`. Query parameters do not affect endpoint selection. -Readiness defaults to false. Older Core versions can supply a callback that -invokes `PrometheusExporter::export()` on their existing exporter, with the -Toolkit handle owning the listener. +Readiness defaults to false. The Toolkit handle owns the listener lifecycle. ## Requirements diff --git a/toolkit/rust/tests/prometheus_server.rs b/toolkit/rust/tests/prometheus_server.rs index cd895b82..dbdd7c67 100644 --- a/toolkit/rust/tests/prometheus_server.rs +++ b/toolkit/rust/tests/prometheus_server.rs @@ -1,6 +1,5 @@ #![cfg(feature = "prometheus-server")] -use apcore::{MetricsCollector, PrometheusExporter, UsageCollector}; use apcore_toolkit::PrometheusServer; use std::io::ErrorKind; use std::net::{IpAddr, Ipv4Addr, SocketAddr}; @@ -32,17 +31,20 @@ fn split_response(response: &str) -> (&str, &str) { } #[tokio::test] -async fn serves_the_legacy_metrics_text_with_routes_and_live_readiness() { - let metrics = MetricsCollector::new(); - let usage = UsageCollector::new(); - let legacy = PrometheusExporter::new(metrics.clone()).with_usage_collector(usage.clone()); - legacy.start(0, "/metrics").await.unwrap(); - let legacy_address = SocketAddr::from(([127, 0, 0, 1], legacy.local_addr().unwrap().port())); - +async fn serves_the_supplied_metrics_text_with_routes_and_live_readiness() { + const METRICS: &str = + "# TYPE example_calls_total counter\nexample_calls_total{site=\"\u{8bfe}\u{5802}\"} 1\n"; + let has_metrics = Arc::new(AtomicBool::new(false)); let ready = Arc::new(AtomicBool::new(false)); let mut server = PrometheusServer::new({ - let snapshot = legacy.clone(); - move || snapshot.export() + let has_metrics = Arc::clone(&has_metrics); + move || { + if has_metrics.load(Ordering::Relaxed) { + METRICS.to_string() + } else { + String::new() + } + } }) .with_metrics_path("/custom") .with_readiness({ @@ -60,23 +62,15 @@ async fn serves_the_legacy_metrics_text_with_routes_and_live_readiness() { assert!(headers .to_ascii_lowercase() .contains("content-type: text/plain; version=0.0.4; charset=utf-8")); - let old = request(legacy_address, "GET", "/metrics").await; - assert_eq!(body, split_response(&old).1); - for name in [ - "apcore_module_calls_total", - "apcore_module_errors_total", - "apcore_module_duration_seconds", - ] { - assert!(body.contains(name)); - } + assert!(body.is_empty()); - metrics.increment_calls("sample.metric", "success"); - usage.record("sample.metric", Some("sample.caller"), 1.0, true); + has_metrics.store(true, Ordering::Relaxed); let populated = request(address, "GET", "/custom").await; - let old = request(legacy_address, "GET", "/metrics").await; - let body = split_response(&populated).1; - assert_eq!(body, split_response(&old).1); - assert!(body.contains("apcore_usage_")); + let (headers, body) = split_response(&populated); + assert_eq!(body, METRICS); + assert!(headers + .to_ascii_lowercase() + .contains(&format!("content-length: {}", METRICS.len()))); assert!(request(address, "GET", "/metrics").await.contains("404")); let rejected = request(address, "POST", "/custom").await; @@ -104,7 +98,6 @@ async fn serves_the_legacy_metrics_text_with_routes_and_live_readiness() { TcpStream::connect(address).await.unwrap_err().kind(), ErrorKind::ConnectionRefused ); - legacy.shutdown(); } #[tokio::test] diff --git a/toolkit/typescript/README.md b/toolkit/typescript/README.md index 80ed64df..f7ba199b 100644 --- a/toolkit/typescript/README.md +++ b/toolkit/typescript/README.md @@ -35,15 +35,14 @@ callback reports ready. ```typescript import { once } from 'node:events'; -import { MetricsCollector, PrometheusExporter, UsageCollector } from 'apcore-js'; +import { MetricsCollector, UsageCollector, renderPrometheusMetrics } from 'apcore-js/observability'; import { createPrometheusServer } from 'apcore-toolkit'; const metrics = new MetricsCollector(); const usage = new UsageCollector(); -const exporter = new PrometheusExporter({ collector: metrics, usageCollector: usage }); let ready = false; const server = createPrometheusServer({ - renderMetrics: () => exporter.export(), + renderMetrics: () => renderPrometheusMetrics(metrics, usage), isReady: () => ready, }); const listening = once(server, 'listening'); @@ -55,8 +54,8 @@ process.once('SIGTERM', () => { server.close(); }); Use the same collector instances that your APCore middleware writes to. The returned Node server lets the application choose the bind address, handle -listen errors and wait for active responses to finish on shutdown. The legacy -Core exporter and its lifecycle API are available. +listen errors and wait for active responses to finish on shutdown. The +`apcore-js/observability` entry point is available starting with Core alpha.2. ### ScannedModule diff --git a/toolkit/typescript/tests/prometheus-server.test.ts b/toolkit/typescript/tests/prometheus-server.test.ts index c3b4f064..46d1f15d 100644 --- a/toolkit/typescript/tests/prometheus-server.test.ts +++ b/toolkit/typescript/tests/prometheus-server.test.ts @@ -1,10 +1,11 @@ -import { MetricsCollector, PrometheusExporter, UsageCollector } from 'apcore-js'; import { once } from 'node:events'; import { request as httpRequest } from 'node:http'; import type { IncomingMessage, Server, ServerResponse } from 'node:http'; import { describe, expect, it, vi } from 'vitest'; import { createPrometheusServer } from '../src/index.js'; +const metricsText = '# TYPE example_calls_total counter\nexample_calls_total{site="\u8bfe\u5802"} 1\n'; + function request(server: Server, url: string, method = 'GET') { const response = { writeHead: vi.fn().mockReturnThis(), end: vi.fn() }; server.emit('request', { url, method } as IncomingMessage, response as unknown as ServerResponse); @@ -56,17 +57,11 @@ describe('createPrometheusServer', () => { }, ); - it('serves the exact legacy collector output for a custom path', () => { - const collector = new MetricsCollector(); - const usageCollector = new UsageCollector(); - collector.increment('apcore_test_calls_total', {}, 2); - usageCollector.record('learning.review', 12, false); - const exporter = new PrometheusExporter({ collector, usageCollector }); - const server = createPrometheusServer({ renderMetrics: () => exporter.export(), metricsPath: '/scrape' }); + it('serves the supplied metrics text for a custom path', () => { + const server = createPrometheusServer({ renderMetrics: () => metricsText, metricsPath: '/scrape' }); const reply = request(server, '/scrape'); - const body = Buffer.from(exporter.export(), 'utf8'); - expect(body.toString()).toContain('apcore_usage_calls_total'); + const body = Buffer.from(metricsText, 'utf8'); expect(reply.writeHead).toHaveBeenCalledWith(200, { 'Content-Type': 'text/plain; version=0.0.4; charset=utf-8', 'Content-Length': String(body.length), @@ -133,33 +128,22 @@ describe('createPrometheusServer', () => { } }); - it('returns matching bytes from the legacy and Toolkit listeners for empty and live collectors', async () => { - const collector = new MetricsCollector(); - const usageCollector = new UsageCollector(); - const exporter = new PrometheusExporter({ collector, usageCollector }); - const server = createPrometheusServer({ renderMetrics: () => exporter.export() }); + it('renders current metrics on every scrape', async () => { + let text = ''; + const server = createPrometheusServer({ renderMetrics: () => text }); const port = await listen(server); try { - exporter.start({ port: 0 }); - // The legacy wrapper does not expose its chosen ephemeral port. - const legacyServer = Reflect.get(exporter, '_server') as Server; - if (!legacyServer.listening) await once(legacyServer, 'listening'); - const legacyPort = serverPort(legacyServer); - const cold = await scrape(port, '/metrics'); expect(cold.status).toBe(200); expect(cold.headers['content-length']).toBe('0'); - expect(cold.body).toEqual((await scrape(legacyPort, '/metrics')).body); - - collector.increment('apcore_test_calls_total', {}, 2); - usageCollector.record('study.review', 12, false); + expect(cold.body.length).toBe(0); + text = metricsText; const live = await scrape(port, '/metrics'); expect(live.status).toBe(200); - expect(live.body.toString()).toContain('apcore_usage_calls_total'); - expect(live.body).toEqual((await scrape(legacyPort, '/metrics')).body); - expect(live.body).toEqual(Buffer.from(exporter.export(), 'utf8')); + expect(live.body).toEqual(Buffer.from(metricsText, 'utf8')); + expect(live.headers['content-length']).toBe(String(live.body.length)); } finally { - await Promise.all([exporter.stop(), close(server)]); + await close(server); } }); From b6b53ba5a15aba1f30336ec9a07fa49b4fd0d987 Mon Sep 17 00:00:00 2001 From: tercel Date: Fri, 27 Nov 2026 16:30:49 +0800 Subject: [PATCH 3/9] refactor(a2a): select Rust subscribers per host Signed-off-by: tercel --- a2a/rust/README.md | 24 +++--- a2a/rust/src/event_subscriber.rs | 10 +-- .../tests/event_subscriber_conformance.rs | 75 +++++++------------ 3 files changed, 44 insertions(+), 65 deletions(-) diff --git a/a2a/rust/README.md b/a2a/rust/README.md index 860a918e..34378746 100644 --- a/a2a/rust/README.md +++ b/a2a/rust/README.md @@ -163,20 +163,26 @@ let auth = JWTAuthenticator::new("your-secret-key") ### Deliver Core events over A2A -Register the optional transport before creating the Core client that loads your -subscriber configuration: +Register the optional transport in the subscriber registry for the Core client +that will load your configuration. ```rust -use apcore::{APCore, ModuleError}; +use apcore::{APCore, APCoreOptions, Config, SubscriberRegistry}; use apcore_a2a::register_a2a_subscriber; -fn load_core() -> Result { - register_a2a_subscriber(); - APCore::from_path("apcore.yaml") +fn load_core() -> Result> { + let mut subscribers = SubscriberRegistry::new(); + register_a2a_subscriber(&mut subscribers); + let options = APCoreOptions { + config: Some(Config::load(std::path::Path::new("apcore.yaml"))?), + fail_on_error: true, + ..Default::default() + }; + Ok(APCore::try_start_with_subscribers(options, &subscribers)?) } ``` -This selects the transport for subsequently created `type: a2a` subscribers, +This selects the transport for this client's `type: a2a` subscribers, including `filter` entries whose `delegate_type` is `a2a`. `platform_url`, `auth`, `skill_id`, `timeout_ms`, and `retry` use the existing configuration layout. Core manages retries, circuit breaking, and dead letters. Configured @@ -184,9 +190,7 @@ retry and dead-letter delivery requires a Core release whose circuit wrapper reports failed attempts to the emitter. The A2A transport uses this crate's existing HTTP client dependency and works without Core's `events` feature. -To restore Core's built-in transport, restart the process without the registration -call and enable Core's `events` feature for built-in HTTP delivery. Subscribers -created before registration retain the transport selected at creation time. +Other Core clients can configure their own subscriber registries in the same process. ## Architecture diff --git a/a2a/rust/src/event_subscriber.rs b/a2a/rust/src/event_subscriber.rs index 7ca19a7a..a8cabf81 100644 --- a/a2a/rust/src/event_subscriber.rs +++ b/a2a/rust/src/event_subscriber.rs @@ -6,8 +6,7 @@ use std::sync::OnceLock; use std::time::Duration; use apcore::{ - register_subscriber_type, ApCoreEvent, ErrorCode, EventRetryConfig, EventSubscriber, - ModuleError, + ApCoreEvent, ErrorCode, EventRetryConfig, EventSubscriber, ModuleError, SubscriberRegistry, }; use reqwest::header::{HeaderMap, HeaderName, HeaderValue, AUTHORIZATION}; use serde_json::{json, Value}; @@ -143,10 +142,9 @@ impl EventSubscriber for A2AEventSubscriber { } } -/// Select the A2A transport for future `type: a2a` configuration entries. -/// Existing subscriptions are owned by their original emitter. -pub fn register_a2a_subscriber() { - register_subscriber_type("a2a", Box::new(from_config)); +/// Register the A2A transport for a host's configured subscribers. +pub fn register_a2a_subscriber(registry: &mut SubscriberRegistry) { + registry.register("a2a", from_config); } #[allow(clippy::result_large_err)] // The Core factory contract uses ModuleError. diff --git a/a2a/rust/tests/event_subscriber_conformance.rs b/a2a/rust/tests/event_subscriber_conformance.rs index 2a7e6ee8..0d63422f 100644 --- a/a2a/rust/tests/event_subscriber_conformance.rs +++ b/a2a/rust/tests/event_subscriber_conformance.rs @@ -2,8 +2,7 @@ use std::sync::{Arc, Mutex}; use std::time::Duration; use apcore::{ - create_subscriber, reset_subscriber_registry, APCore, ApCoreEvent, Config, EventSubscriber, - ModuleError, + APCore, APCoreOptions, ApCoreEvent, Config, EventSubscriber, ModuleError, SubscriberRegistry, }; use apcore_a2a::{register_a2a_subscriber, A2AEventSubscriber}; use axum::{extract::State, http::HeaderMap, http::StatusCode, routing::post, Json, Router}; @@ -76,7 +75,11 @@ async fn record_request( state.status } -async fn emit_from_config(subscriber: &Value, event: &ApCoreEvent) -> Vec { +async fn emit_from_config( + subscribers: &SubscriberRegistry, + subscriber: &Value, + event: &ApCoreEvent, +) -> Vec { let project = tempfile::tempdir().unwrap(); let path = project.path().join("apcore.yaml"); std::fs::write( @@ -88,7 +91,15 @@ async fn emit_from_config(subscriber: &Value, event: &ApCoreEvent) -> Vec Vec 0 { - continue; - } - run_case(case, &fixture.event).await; + run_case(&subscribers, case, &fixture.event).await; } - reset_subscriber_registry(); - assert!(format!("{:?}", create_subscriber(&config).unwrap()).starts_with("A2ASubscriber")); } From bb904ab2bfe6950f2f671fc36084d851c1a08e4c Mon Sep 17 00:00:00 2001 From: tercel Date: Fri, 27 Nov 2026 16:36:07 +0800 Subject: [PATCH 4/9] refactor(a2a): select Python subscribers per host Signed-off-by: tercel --- a2a/python/README.md | 22 ++--- a2a/python/src/apcore_a2a/event_subscriber.py | 8 +- .../conformance/test_event_subscriber.py | 80 +++++++------------ 3 files changed, 43 insertions(+), 67 deletions(-) diff --git a/a2a/python/README.md b/a2a/python/README.md index b154f215..566c2a38 100644 --- a/a2a/python/README.md +++ b/a2a/python/README.md @@ -180,17 +180,18 @@ serve(registry, auth=auth) ### A2A event subscriptions -Call `register_a2a_subscriber()` during application startup, before creating the -APCore client. Existing `sys_modules.events.subscribers` entries with -`type: a2a` then use the adapter's HTTP transport. The same factory resolves +Register the A2A factory on the APCore client's subscriber registry. The +client uses the factory for `type: a2a` configuration entries, including `delegate_type: a2a` in a filter. ```python -from apcore import APCore, Config +from apcore.events import SubscriberRegistry +from apcore.full import APCore, Config from apcore_a2a import register_a2a_subscriber -register_a2a_subscriber() -client = APCore(config=Config.discover()) +subscribers = SubscriberRegistry() +register_a2a_subscriber(subscribers) +client = APCore(config=Config.discover(), subscriber_registry=subscribers) try: # Use the client with the application's configured subscribers. pass @@ -200,14 +201,7 @@ finally: The transport uses `httpx` and sends one delivery attempt to the configured `platform_url`. APCore applies retry, circuit breaker and dead-letter policy. -Core 0.33.0's configuration-driven circuit breaker records failures without -forwarding them to the retry and dead-letter pipeline. Use a Core release with -that forwarding enabled when those guarantees are required. - -The factory change applies to future APCore clients in the process. To restore -the built-in transport, remove the registration call and restart with the same -subscriber configuration. The built-in transport requires the optional -`apcore[events]` extra. +Each client can use its own subscriber registry. ### `serve()` diff --git a/a2a/python/src/apcore_a2a/event_subscriber.py b/a2a/python/src/apcore_a2a/event_subscriber.py index c91f979a..0fa92208 100644 --- a/a2a/python/src/apcore_a2a/event_subscriber.py +++ b/a2a/python/src/apcore_a2a/event_subscriber.py @@ -8,7 +8,7 @@ from typing import Any import httpx -from apcore import ApCoreEvent, EventRetryConfig, register_subscriber_type +from apcore.events import ApCoreEvent, EventRetryConfig, SubscriberRegistry _logger = logging.getLogger(__name__) @@ -63,6 +63,6 @@ def _from_config(config: dict[str, Any]) -> A2AEventSubscriber: ) -def register_a2a_subscriber() -> None: - """Select the A2A transport for future `type: a2a` config entries.""" - register_subscriber_type("a2a", _from_config) +def register_a2a_subscriber(registry: SubscriberRegistry) -> None: + """Register the A2A transport for a host's configured subscribers.""" + registry.register("a2a", _from_config) diff --git a/a2a/python/tests/conformance/test_event_subscriber.py b/a2a/python/tests/conformance/test_event_subscriber.py index 19f04656..7843847e 100644 --- a/a2a/python/tests/conformance/test_event_subscriber.py +++ b/a2a/python/tests/conformance/test_event_subscriber.py @@ -10,22 +10,15 @@ from pathlib import Path from threading import Thread from typing import Any -from unittest.mock import patch import pytest -from apcore import APCore, ApCoreEvent, Config, EventEmitter, EventRetryConfig, reset_subscriber_registry -from apcore.events import A2ASubscriber as CoreA2ASubscriber -from apcore.events import CircuitBreakerWrapper, create_subscriber_from_config +from apcore.events import ApCoreEvent, EventEmitter, EventRetryConfig, SubscriberRegistry +from apcore.full import APCore, Config from apcore_a2a import A2AEventSubscriber, register_a2a_subscriber _FIXTURE = json.loads((Path(__file__).resolve().parents[3] / "conformance/fixtures/event_subscriber.json").read_text()) _DELIVERY_EVENTS = ("apcore.event.delivery_failed", "apcore.subscriber.circuit_opened") -_LEGACY_FAILURE_COUNTS = { - "transient_failure": {"requests": 1, "dead_letters": 0}, - "circuit_breaker": {"requests": 1, "dead_letters": 0}, - "timeout": {"requests": 1, "dead_letters": 0}, -} class _DiagnosticSink: @@ -37,15 +30,6 @@ async def on_event(self, event: ApCoreEvent) -> None: self._events.append(event) -@pytest.fixture(autouse=True) -def _isolate_subscriber_registry() -> Iterator[None]: - reset_subscriber_registry() - try: - yield - finally: - reset_subscriber_registry() - - @contextmanager def _receiver( status: int = 204, delay_ms: int = 0 @@ -76,14 +60,18 @@ def log_message(self, format: str, *args: object) -> None: worker.join(timeout=3) -def _emit_from_config(path: Path, subscriber: dict[str, Any]) -> list[ApCoreEvent]: +def _emit_from_config( + path: Path, + subscriber: dict[str, Any], + registry: SubscriberRegistry, +) -> list[ApCoreEvent]: path.write_text( "version: '1.0.0'\nproject: {name: fixture}\n" "sys_modules:\n enabled: true\n events:\n enabled: true\n" f" subscribers: {json.dumps([subscriber])}\n" ) events: list[ApCoreEvent] = [] - with closing(APCore(config=Config.load(str(path)))) as core: + with closing(APCore(config=Config.load(str(path)), subscriber_registry=registry)) as core: assert core.events is not None for name in _DELIVERY_EVENTS: core.events.subscribe(_DiagnosticSink(name, events)) @@ -102,16 +90,12 @@ def test_event_subscriber_from_config(case: dict[str, Any], tmp_path: Path) -> N else: subscriber.update(platform_url=url, id="configured-a2a") - register_a2a_subscriber() - register_a2a_subscriber() - with patch("apcore.events.subscribers.aiohttp", None): - events = _emit_from_config(tmp_path / "apcore.yaml", subscriber) + registry = SubscriberRegistry() + register_a2a_subscriber(registry) + register_a2a_subscriber(registry) + events = _emit_from_config(tmp_path / "apcore.yaml", subscriber, registry) expected = case["expected"] - if not hasattr(CircuitBreakerWrapper, "retry"): - # The released minimum's Config wrapper counts failures for its - # circuit without forwarding them to the emitter's retry loop. - expected = {**expected, **_LEGACY_FAILURE_COUNTS.get(case["id"], {})} assert len(received) == expected["requests"] for headers, body in received: assert headers.get("content-type") == "application/json" @@ -125,29 +109,27 @@ def test_event_subscriber_from_config(case: dict[str, Any], tmp_path: Path) -> N assert event.data["subscriber_id"] == "configured-a2a" -def test_subscriber_factory_switch_is_opt_in_and_reversible() -> None: +def test_subscriber_factory_is_opt_in() -> None: config = {"type": "a2a", "platform_url": "https://example.com/receive"} - assert isinstance(create_subscriber_from_config(config), CoreA2ASubscriber) - register_a2a_subscriber() - assert isinstance(create_subscriber_from_config(config), A2AEventSubscriber) - reset_subscriber_registry() - assert isinstance(create_subscriber_from_config(config), CoreA2ASubscriber) - - -def test_legacy_config_restored_after_reset(tmp_path: Path) -> None: - pytest.importorskip("aiohttp", reason="the legacy Core transport uses the optional events extra") + registry = SubscriberRegistry() + register_a2a_subscriber(registry) + assert isinstance(registry.create(config), A2AEventSubscriber) + with pytest.raises(ValueError, match="a2a"): + SubscriberRegistry().create(config) + + +def test_two_hosts_keep_independent_subscriber_factories(tmp_path: Path) -> None: + first, second = SubscriberRegistry(), SubscriberRegistry() + register_a2a_subscriber(first) + second.register( + "a2a", + lambda config: A2AEventSubscriber(config["platform_url"], skill_id="second.host"), + ) with _receiver() as (url, received): - config_path = tmp_path / "apcore.yaml" - subscriber = {"type": "a2a", "platform_url": url, "auth": "test-token"} - register_a2a_subscriber() - assert _emit_from_config(config_path, subscriber) == [] - assert len(received) == 1 - - reset_subscriber_registry() - assert _emit_from_config(config_path, subscriber) == [] - assert len(received) == 2 - assert received[0][0]["authorization"] == received[1][0]["authorization"] == "Bearer test-token" - assert received[0][1] == received[1][1] + subscriber = {"type": "a2a", "platform_url": url} + assert _emit_from_config(tmp_path / "first.yaml", subscriber, first) == [] + assert _emit_from_config(tmp_path / "second.yaml", subscriber, second) == [] + assert [payload["skillId"] for _, payload in received] == ["apevo.event_receiver", "second.host"] async def test_zero_timeout_leaves_delivery_to_the_event_bus() -> None: From 3af414502490a853b7b338b570a8ff1724ae4644 Mon Sep 17 00:00:00 2001 From: tercel Date: Fri, 27 Nov 2026 16:46:19 +0800 Subject: [PATCH 5/9] refactor(a2a): inject TypeScript subscriber factories per host Signed-off-by: tercel --- a2a/typescript/README.md | 27 ++++---- a2a/typescript/src/event-subscriber.ts | 27 ++++---- a2a/typescript/src/index.ts | 2 +- .../conformance/event-subscriber.test.ts | 69 ++++++++++--------- 4 files changed, 64 insertions(+), 61 deletions(-) diff --git a/a2a/typescript/README.md b/a2a/typescript/README.md index 21e74fbc..2d3263a9 100644 --- a/a2a/typescript/README.md +++ b/a2a/typescript/README.md @@ -189,17 +189,20 @@ client.close(); ### Deliver APCore events to an A2A receiver -Call `registerA2ASubscriber()` during startup before constructing any APCore -client that should use the A2A transport. The existing `type: a2a` configuration -selects one subscriber, including when used as a filter delegate. Importing -the adapter leaves the built-in Core registration in place. +Supply the A2A subscriber factory when constructing the APCore client. +The client's `type: a2a` setting selects the factory, including for filter delegates. ```typescript -import { APCore, Config, createEvent } from "apcore-js"; -import { registerA2ASubscriber } from "apcore-a2a"; - -registerA2ASubscriber(); -const core = new APCore({ config: Config.load("apcore.yaml") }); +import { Config } from "apcore-js/config"; +import { createEvent } from "apcore-js/events"; +import { APCore } from "apcore-js/full"; +import { createSysModulesPlugin } from "apcore-js/sys-modules"; +import { createA2AEventSubscriber } from "apcore-a2a"; + +const core = new APCore({ + config: Config.load("apcore.yaml"), + plugins: [createSysModulesPlugin({ subscriberFactories: { a2a: createA2AEventSubscriber } })], +}); core.events?.emit(createEvent("example.updated", "example.module", "info", { value: 42 })); await core.events?.flush(); ``` @@ -224,11 +227,7 @@ sys_modules: An omitted `skill_id` defaults to `apevo.event_receiver`. A string `auth` sends a bearer token, and a header map supplies custom headers. The transport uses Node's fetch and sends one POST per attempt. APCore owns filter rules, -retry, circuit breakers, and dead-letter delivery. Configured retries and -dead-letter reporting require a Core build that propagates delivery failures -through the circuit breaker. Core 0.33.0 keeps its existing configured event -handling. To return to the built-in transport, omit the registration call -when restarting your application. +retry, circuit breakers, and dead-letter delivery. ### Add authentication diff --git a/a2a/typescript/src/event-subscriber.ts b/a2a/typescript/src/event-subscriber.ts index 55d69fba..7b279f92 100644 --- a/a2a/typescript/src/event-subscriber.ts +++ b/a2a/typescript/src/event-subscriber.ts @@ -1,5 +1,4 @@ -import { registerSubscriberType } from "apcore-js"; -import type { ApCoreEvent, EventRetryConfig, EventSubscriber } from "apcore-js"; +import type { ApCoreEvent, EventRetryConfig, EventSubscriber } from "apcore-js/events"; export interface A2AEventSubscriberOptions { readonly timeoutMs?: number; @@ -92,18 +91,16 @@ function retryFromConfig(value: unknown): EventRetryConfig | undefined { return retry; } -/** Select this transport for future `type: a2a` entries, including filter delegates. */ -export function registerA2ASubscriber(): void { - registerSubscriberType("a2a", config => { - const { platform_url: url, auth, id, timeout_ms: timeoutMs, skill_id: skillId, retry } = config; - if (typeof url !== "string" || url.length === 0) { - throw new Error('a2a subscriber requires a non-empty "platform_url" string field'); - } - return new A2AEventSubscriber(url, auth as AuthHeaders | undefined, { - id: typeof id === "string" ? id : undefined, - timeoutMs: typeof timeoutMs === "number" ? timeoutMs : undefined, - skillId: typeof skillId === "string" ? skillId : undefined, - retry: retryFromConfig(retry), - }); +/** Build this host's transport for a configured A2A subscriber or filter delegate. */ +export function createA2AEventSubscriber(config: Record): A2AEventSubscriber { + const { platform_url: url, auth, id, timeout_ms: timeoutMs, skill_id: skillId, retry } = config; + if (typeof url !== "string" || url.length === 0) { + throw new Error('a2a subscriber requires a non-empty "platform_url" string field'); + } + return new A2AEventSubscriber(url, auth as AuthHeaders | undefined, { + id: typeof id === "string" ? id : undefined, + timeoutMs: typeof timeoutMs === "number" ? timeoutMs : undefined, + skillId: typeof skillId === "string" ? skillId : undefined, + retry: retryFromConfig(retry), }); } diff --git a/a2a/typescript/src/index.ts b/a2a/typescript/src/index.ts index 0783bd93..e7292b11 100644 --- a/a2a/typescript/src/index.ts +++ b/a2a/typescript/src/index.ts @@ -19,7 +19,7 @@ export { } from "./client/index.js"; // Events -export { A2AEventSubscriber, registerA2ASubscriber } from "./event-subscriber.js"; +export { A2AEventSubscriber, createA2AEventSubscriber } from "./event-subscriber.js"; export type { A2AEventSubscriberOptions } from "./event-subscriber.js"; // Auth diff --git a/a2a/typescript/tests/conformance/event-subscriber.test.ts b/a2a/typescript/tests/conformance/event-subscriber.test.ts index f533fc09..78e85445 100644 --- a/a2a/typescript/tests/conformance/event-subscriber.test.ts +++ b/a2a/typescript/tests/conformance/event-subscriber.test.ts @@ -1,7 +1,7 @@ -import { - APCore, A2ASubscriber, Config, VERSION, createSubscriberFromConfig, resetSubscriberRegistry, -} from "apcore-js"; -import type { ApCoreEvent, EventEmitter } from "apcore-js"; +import { Config } from "apcore-js/config"; +import type { ApCoreEvent, EventEmitter } from "apcore-js/events"; +import { APCore } from "apcore-js/full"; +import { createSysModulesPlugin } from "apcore-js/sys-modules"; import { once } from "node:events"; import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { createServer } from "node:http"; @@ -9,7 +9,7 @@ import type { IncomingHttpHeaders } from "node:http"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { describe, expect, it } from "vitest"; -import { A2AEventSubscriber, registerA2ASubscriber } from "../../src/index.js"; +import { A2AEventSubscriber, createA2AEventSubscriber } from "../../src/index.js"; interface FixtureCase { id: string; @@ -44,12 +44,12 @@ interface RecordedRequest { const fixture = JSON.parse(readFileSync( new URL("../../../conformance/fixtures/event_subscriber.json", import.meta.url), "utf8", )) as { event: FixtureEvent; test_cases: FixtureCase[] }; -// The published minimum suppresses failures from configured subscribers -// inside CircuitBreakerWrapper. Candidate jobs can require all cases even -// when checking their installation, so a stale minimum cannot pass them. -const legacyCoreFloor = VERSION === "0.33.0" && process.env.APCORE_A2A_REQUIRE_RELIABLE_DELIVERY !== "1"; - -function createEmitter(configFile: string, receiverUrl: string, test: FixtureCase): EventEmitter { +function createEmitter( + configFile: string, + receiverUrl: string, + test: FixtureCase, + factory = createA2AEventSubscriber, +): EventEmitter { const subscriber = test.subscriber.type === "filter" ? { ...test.subscriber, delegate_config: { platform_url: receiverUrl } } : { ...test.subscriber, platform_url: receiverUrl }; @@ -62,7 +62,11 @@ function createEmitter(configFile: string, receiverUrl: string, test: FixtureCas " enabled: true", ` subscribers: ${JSON.stringify([subscriber])}`, ].join("\n")); - const app = new APCore({ config: Config.load(configFile), failOnError: true }); + const app = new APCore({ + config: Config.load(configFile), + failOnError: true, + plugins: [createSysModulesPlugin({ subscriberFactories: { a2a: factory } })], + }); if (!app.events) throw new Error("Configured event bus is unavailable"); return app.events; } @@ -76,13 +80,12 @@ function expectRequest(recorded: RecordedRequest, expected: FixtureCase["expecte expect(recorded.body).toEqual({ skillId: expected.skill_id, event: fixture.event }); } -it("assigns distinct generated IDs to legacy and Surface A2A subscribers", () => { - const core = new A2ASubscriber("https://example.invalid/core"); +it("assigns distinct generated IDs to Surface A2A subscribers", () => { const surface = new A2AEventSubscriber("https://example.invalid/surface"); const secondSurface = new A2AEventSubscriber("https://example.invalid/another"); - expect(new Set([core.subscriberId, surface.subscriberId, secondSurface.subscriberId]).size).toBe(3); + expect(surface.subscriberId).not.toBe(secondSurface.subscriberId); expect(surface.subscriberId).toMatch(/^a2a-\d+$/); - expect(surface.subscriberType).toBe(core.subscriberType); + expect(surface.subscriberType).toBe("a2a"); expect(new A2AEventSubscriber("https://example.invalid/explicit", undefined, { id: "receiver" }).subscriberId).toBe("receiver"); }); @@ -110,7 +113,6 @@ describe("configured A2A event subscriber", () => { }); }); const scratch = mkdtempSync(join(tmpdir(), "apcore-a2a-event-")); - resetSubscriberRegistry(); try { const listening = once(server, "listening"); server.listen(0, "127.0.0.1"); @@ -127,10 +129,6 @@ describe("configured A2A event subscriber", () => { data: fixture.event.data, }; - const config = { type: "a2a", platform_url: url }; - expect(createSubscriberFromConfig(config)).toBeInstanceOf(A2ASubscriber); - registerA2ASubscriber(); - expect(createSubscriberFromConfig(config)).toBeInstanceOf(A2AEventSubscriber); const emitter = createEmitter(configFile, url, test); try { for (const eventPattern of ["apcore.event.delivery_failed", "apcore.subscriber.circuit_opened"]) { @@ -153,20 +151,29 @@ describe("configured A2A event subscriber", () => { } if (test.id === "bearer_success") { - resetSubscriberRegistry(); - expect(createSubscriberFromConfig(config)).toBeInstanceOf(A2ASubscriber); - const legacy = createEmitter(configFile, url, test); + const secondSkill = "fixture.second"; + const second = createEmitter(configFile, url, test, config => + createA2AEventSubscriber({ ...config, skill_id: secondSkill }), + ); + const first = createEmitter(configFile, url, test); try { - legacy.emit(event); - await legacy.flush(); + second.emit(event); + first.emit(event); + await Promise.all([second.flush(), first.flush()]); } finally { - await legacy.shutdown(); + await Promise.all([second.shutdown(), first.shutdown()]); + } + expect(requests).toHaveLength(3); + const expectedSkills = [test.expected.skill_id, secondSkill]; + for (const expectedSkill of expectedSkills) { + const deliveries = requests.slice(1).filter(request => + (request.body as { skillId: string }).skillId === expectedSkill, + ); + expect(deliveries).toHaveLength(1); + expectRequest(deliveries[0], { ...test.expected, skill_id: expectedSkill }); } - expect(requests).toHaveLength(2); - expectRequest(requests[1], test.expected); } } finally { - resetSubscriberRegistry(); if (server.listening) { const closed = once(server, "close"); server.close(); @@ -178,6 +185,6 @@ describe("configured A2A event subscriber", () => { }; for (const test of fixture.test_cases) { - it.skipIf(legacyCoreFloor && test.expected.dead_letters > 0)(test.id, () => verifyDelivery(test)); + it(test.id, () => verifyDelivery(test)); } }); From b0dcd321ee01c0cb88806adff7da7bc3fec16188 Mon Sep 17 00:00:00 2001 From: tercel Date: Fri, 27 Nov 2026 17:37:37 +0800 Subject: [PATCH 6/9] refactor(surfaces): adopt Core profiles and own tool projections Signed-off-by: tercel --- a2a/python/pyproject.toml | 8 +- a2a/python/src/apcore_a2a/__main__.py | 5 +- a2a/python/src/apcore_a2a/_serve.py | 2 +- a2a/python/src/apcore_a2a/openapi_backend.py | 2 +- a2a/python/src/apcore_a2a/server/factory.py | 6 +- .../tests/server/test_system_modules.py | 8 +- a2a/python/tests/test_cli.py | 26 +- a2a/rust/Cargo.lock | 10 +- a2a/rust/Cargo.toml | 6 +- a2a/rust/tests/integration.rs | 13 +- a2a/typescript/package.json | 6 +- a2a/typescript/pnpm-lock.yaml | 31 +- a2a/typescript/src/cli.ts | 2 +- a2a/typescript/src/config.ts | 2 +- a2a/typescript/src/openapi-backend.ts | 3 +- a2a/typescript/src/serve.ts | 2 +- a2a/typescript/src/server/factory.ts | 13 +- .../tests/server/system-modules.test.ts | 4 +- cli/README.md | 2 - cli/python/README.md | 2 - cli/python/pyproject.toml | 6 +- cli/python/src/apcore_cli/_sandbox_runner.py | 3 +- cli/python/src/apcore_cli/acl_loader.py | 5 +- cli/python/src/apcore_cli/config.py | 2 +- cli/python/src/apcore_cli/factory.py | 8 +- cli/python/src/apcore_cli/system_cmd.py | 2 +- cli/python/tests/test_e2e.py | 12 +- cli/python/tests/test_sandbox_runner.py | 16 +- cli/python/tests/test_system_cmd.py | 16 +- cli/rust/Cargo.lock | 164 +---- cli/rust/Cargo.toml | 6 +- cli/typescript/package.json | 10 +- cli/typescript/pnpm-lock.yaml | 31 +- cli/typescript/src/acl-loader.ts | 3 +- cli/typescript/src/config.ts | 25 +- cli/typescript/src/security/sandbox.ts | 2 +- cli/typescript/src/system-cmd.ts | 2 +- cli/typescript/tests/acl-governance.test.ts | 3 +- mcp/conformance/README.md | 5 + mcp/conformance/fixtures/tool_projection.json | 74 ++ mcp/docs/features/openai-converter.md | 29 +- mcp/python/pyproject.toml | 8 +- mcp/python/src/apcore_mcp/__init__.py | 4 +- mcp/python/src/apcore_mcp/__main__.py | 6 +- mcp/python/src/apcore_mcp/acl_builder.py | 2 +- mcp/python/src/apcore_mcp/adapters/schema.py | 24 +- mcp/python/src/apcore_mcp/apcore_mcp.py | 7 +- .../src/apcore_mcp/converters/__init__.py | 2 +- .../src/apcore_mcp/converters/anthropic.py | 31 + .../src/apcore_mcp/converters/openai.py | 32 +- .../src/apcore_mcp/middleware_builder.py | 7 +- mcp/python/src/apcore_mcp/openapi_backend.py | 2 +- mcp/python/tests/converters/test_openai.py | 35 +- mcp/python/tests/test_acl.py | 4 +- .../tests/test_acl_approval_gating_e2e.py | 2 +- mcp/python/tests/test_apcore_mcp.py | 4 +- mcp/python/tests/test_api.py | 12 +- mcp/python/tests/test_cli.py | 12 +- mcp/python/tests/test_config_bus_overrides.py | 18 +- mcp/python/tests/test_d4_d9_d10_d11_fixes.py | 2 +- mcp/python/tests/test_management_surfaces.py | 4 +- mcp/python/tests/test_middleware.py | 6 +- .../tests/test_openapi_config_bus_wiring.py | 8 +- mcp/python/tests/test_review_fixes.py | 10 +- mcp/python/tests/test_stdio_isolation.py | 2 +- mcp/rust/Cargo.lock | 180 +---- mcp/rust/Cargo.toml | 6 +- mcp/rust/src/adapters/schema.rs | 10 + mcp/rust/src/apcore_mcp.rs | 15 +- mcp/rust/src/converters/anthropic.rs | 35 + mcp/rust/src/converters/mod.rs | 56 ++ mcp/rust/src/converters/openai.rs | 630 ++---------------- mcp/rust/src/lib.rs | 1 + mcp/rust/tests/converters_test.rs | 84 ++- mcp/typescript/package.json | 6 +- mcp/typescript/pnpm-lock.yaml | 31 +- mcp/typescript/src/adapters/schema.ts | 42 +- mcp/typescript/src/apcore-mcp.ts | 2 +- mcp/typescript/src/cli.ts | 11 +- mcp/typescript/src/config.ts | 8 +- mcp/typescript/src/converters/anthropic.ts | 28 + mcp/typescript/src/converters/index.ts | 1 + mcp/typescript/src/converters/openai.ts | 193 +----- mcp/typescript/src/index.ts | 172 ++--- mcp/typescript/src/middleware-builder.ts | 2 +- mcp/typescript/src/openapi-backend.ts | 9 +- .../src/server/async-task-bridge.ts | 2 +- mcp/typescript/src/server/observability.ts | 2 +- mcp/typescript/src/types.ts | 15 + .../tests/acl-approval-gating-e2e.test.ts | 8 +- .../tests/acl-rule-template.test.ts | 6 +- mcp/typescript/tests/cli.test.ts | 31 +- mcp/typescript/tests/config-bus.test.ts | 106 ++- .../tests/converters/openai.test.ts | 50 +- mcp/typescript/tests/fixtures/stdio-cli.ts | 10 +- mcp/typescript/tests/fixtures/stdio-noise.ts | 4 +- .../tests/openapi-backend-wiring.test.ts | 4 +- .../tests/server/scoped-approval.test.ts | 6 +- .../tests/server/stream-completion.test.ts | 9 +- .../tests/system-surface-conformance.test.ts | 6 +- mcp/typescript/vitest.config.ts | 2 + toolkit/python/pyproject.toml | 4 +- .../python/src/apcore_toolkit/ai_enhancer.py | 2 +- .../src/apcore_toolkit/binding_loader.py | 2 +- .../src/apcore_toolkit/formatting/surface.py | 2 +- .../output/http_proxy_writer.py | 5 +- .../apcore_toolkit/output/registry_writer.py | 5 +- toolkit/python/src/apcore_toolkit/scanner.py | 2 +- toolkit/python/src/apcore_toolkit/types.py | 2 +- toolkit/rust/Cargo.lock | 177 +---- toolkit/rust/Cargo.toml | 4 +- toolkit/typescript/package.json | 4 +- toolkit/typescript/pnpm-lock.yaml | 2 +- 113 files changed, 1145 insertions(+), 1670 deletions(-) create mode 100644 mcp/conformance/fixtures/tool_projection.json create mode 100644 mcp/python/src/apcore_mcp/converters/anthropic.py create mode 100644 mcp/rust/src/converters/anthropic.rs create mode 100644 mcp/typescript/src/converters/anthropic.ts diff --git a/a2a/python/pyproject.toml b/a2a/python/pyproject.toml index b226dd26..8443acad 100644 --- a/a2a/python/pyproject.toml +++ b/a2a/python/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "hatchling.build" [project] name = "apcore-a2a" -version = "0.8.8a1" +version = "0.8.8a2" description = "Automatic A2A Protocol Adapter for apcore Module Registry" readme = "README.md" license = "Apache-2.0" @@ -26,8 +26,8 @@ classifiers = [ "Framework :: AsyncIO", ] dependencies = [ - "apcore>=0.33.0,<=1.0.0a1", - "apcore-toolkit==0.15.1a1", + "apcore[config,discovery]==1.0.0a2", + "apcore-toolkit==0.15.1a2", "a2a-sdk[http-server]>=1.1.2", "starlette>=0.40.0", "uvicorn>=0.30.0", @@ -39,7 +39,7 @@ dependencies = [ # The OpenAPI backend fetches a spec over http(s) and registers each operation as # an HTTP proxy, both of which live behind apcore-toolkit's own extra. openapi = [ - "apcore-toolkit[http-proxy]==0.15.1a1", + "apcore-toolkit[http-proxy]==0.15.1a2", ] dev = [ "pytest>=7.0", diff --git a/a2a/python/src/apcore_a2a/__main__.py b/a2a/python/src/apcore_a2a/__main__.py index aa9e37da..84ef14d9 100644 --- a/a2a/python/src/apcore_a2a/__main__.py +++ b/a2a/python/src/apcore_a2a/__main__.py @@ -173,8 +173,6 @@ def _run_serve(args: argparse.Namespace, openapi: object | None = None) -> None: resolved by ``main()`` so the config file is read once. It defaults to ``None`` only so that a direct call in a test need not supply it. """ - from apcore import Registry - # Step 1: Load the registry from whichever backend source(s) were given. # `main()` has already rejected the neither-given case as a usage error. registry = None @@ -189,7 +187,10 @@ def _run_serve(args: argparse.Namespace, openapi: object | None = None) -> None: if not extensions_dir.is_dir(): print(f"Error: Not a directory: {extensions_dir}", file=sys.stderr) sys.exit(1) + from apcore.discovery import Registry + registry = Registry(extensions_dir=str(extensions_dir)) + registry.discover() # `main()` resolved this already; only a direct call needs the fallback. if openapi is None: diff --git a/a2a/python/src/apcore_a2a/_serve.py b/a2a/python/src/apcore_a2a/_serve.py index 61e8028b..6edf40e0 100644 --- a/a2a/python/src/apcore_a2a/_serve.py +++ b/a2a/python/src/apcore_a2a/_serve.py @@ -44,7 +44,7 @@ def _resolve_registry_and_executor( """ # Path shortcut: "./extensions" → Registry + discover + Executor if isinstance(registry_or_executor, str | Path): - from apcore import Registry + from apcore.discovery import Registry from apcore.executor import Executor registry = Registry(extensions_dir=str(registry_or_executor)) diff --git a/a2a/python/src/apcore_a2a/openapi_backend.py b/a2a/python/src/apcore_a2a/openapi_backend.py index 9f99044c..b6d02d0f 100644 --- a/a2a/python/src/apcore_a2a/openapi_backend.py +++ b/a2a/python/src/apcore_a2a/openapi_backend.py @@ -305,7 +305,7 @@ def openapi_backend( timeout — the two are different concerns and apcore-mcp conflates them in Rust. """ try: - from apcore import Registry + from apcore.registry import Registry from apcore_toolkit import HTTPProxyRegistryWriter, validate_effective_proxy_modules from apcore_toolkit.openapi_scanner import OpenAPIScanner, load_spec except ImportError as exc: # pragma: no cover - exercised by the extras matrix diff --git a/a2a/python/src/apcore_a2a/server/factory.py b/a2a/python/src/apcore_a2a/server/factory.py index 3a3ab624..691bf809 100644 --- a/a2a/python/src/apcore_a2a/server/factory.py +++ b/a2a/python/src/apcore_a2a/server/factory.py @@ -427,8 +427,8 @@ def create( # Requires sys_modules=True and an executor that accepts .use() middleware. if sys_modules and hasattr(executor, "use"): try: - from apcore import register_sys_modules from apcore.config import Config + from apcore.sys_modules.registration import register_sys_modules # `sys_modules` is a TOP-LEVEL section of apcore's config # (apcore config.py DEFAULTS), and `register_sys_modules` reads @@ -519,11 +519,11 @@ async def load_task(task_id: str, context: ServerCallContext) -> Task | None: # since register_sys_modules may already add it when sys_modules=True). if hasattr(executor, "use"): try: - from apcore import ObsLoggingMiddleware + from apcore.observability.context_logger import ObsLoggingMiddleware executor.use(ObsLoggingMiddleware()) if metrics and not sys_modules: - from apcore import ErrorHistoryMiddleware + from apcore.middleware.error_history_middleware import ErrorHistoryMiddleware executor.use(ErrorHistoryMiddleware()) except Exception: diff --git a/a2a/python/tests/server/test_system_modules.py b/a2a/python/tests/server/test_system_modules.py index 4b26276d..c715dba8 100644 --- a/a2a/python/tests/server/test_system_modules.py +++ b/a2a/python/tests/server/test_system_modules.py @@ -104,8 +104,8 @@ def test_warns_when_the_control_surface_is_unprotected(registry_with_a_user_modu Reached the way a real deployment reaches it: the operator builds their own apcore stack with `sys_modules.events` enabled — which is what registers the three `system.control.*` write modules — and hands the Executor to this - package. apcore's approval gate warns once and continues when no - `ApprovalHandler` is configured, so those modules stay callable even though + package with an explicit non-strict policy. The gate warns and continues + when no `ApprovalHandler` is configured, so those modules stay callable even though FR-AGC-003 criterion 12 keeps them off the public card. Visibility and invocability are separate questions, and this warning is what stops the card rule being mistaken for a fix to the second. @@ -114,7 +114,9 @@ def test_warns_when_the_control_surface_is_unprotected(registry_with_a_user_modu from apcore.config import Config registry = registry_with_a_user_module - executor = Executor(registry) + from apcore.policy import ExecutionPolicy + + executor = Executor(registry, policy=ExecutionPolicy(strict=False)) register_sys_modules( registry, executor, diff --git a/a2a/python/tests/test_cli.py b/a2a/python/tests/test_cli.py index 2fe336b4..f744a57a 100644 --- a/a2a/python/tests/test_cli.py +++ b/a2a/python/tests/test_cli.py @@ -3,6 +3,7 @@ from __future__ import annotations from argparse import Namespace +from pathlib import Path from unittest.mock import MagicMock, patch import pytest @@ -130,7 +131,7 @@ def test_serve_zero_modules_exits_1(tmp_path, capsys): log_level="info", ) - with patch("apcore.Registry") as mock_registry_cls: + with patch("apcore.discovery.Registry") as mock_registry_cls: mock_reg = MagicMock() mock_reg.list.return_value = [] mock_registry_cls.return_value = mock_reg @@ -143,6 +144,15 @@ def test_serve_zero_modules_exits_1(tmp_path, capsys): assert "No modules" in captured.err +def test_cli_discovers_files_before_starting_the_server(): + extensions = Path(__file__).resolve().parents[1] / "examples" / "extensions" + with patch("apcore_a2a.serve") as serve: + _run_serve(_ns(extensions_dir=str(extensions)), openapi={}) + + registry = serve.call_args.args[0] + assert registry.list() == ["greeting", "math_calc", "text_echo"] + + # --------------------------------------------------------------------------- # _run_serve() — auth validation # --------------------------------------------------------------------------- @@ -175,7 +185,7 @@ def test_serve_auth_bearer_missing_key_exits_1(tmp_path, capsys, monkeypatch): log_level="info", ) - with patch("apcore.Registry") as mock_registry_cls: + with patch("apcore.discovery.Registry") as mock_registry_cls: mock_reg = MagicMock() mock_reg.list.return_value = ["my.module"] mock_registry_cls.return_value = mock_reg @@ -212,7 +222,7 @@ def test_serve_auth_bearer_with_key(tmp_path, monkeypatch): log_level="info", ) - with patch("apcore.Registry") as mock_registry_cls, patch("apcore_a2a.serve") as mock_serve: + with patch("apcore.discovery.Registry") as mock_registry_cls, patch("apcore_a2a.serve") as mock_serve: mock_reg = MagicMock() mock_reg.list.return_value = ["my.module"] mock_registry_cls.return_value = mock_reg @@ -248,7 +258,7 @@ def test_serve_auth_bearer_with_jwt_secret_env(tmp_path, monkeypatch, capsys): log_level="info", ) - with patch("apcore.Registry") as mock_registry_cls, patch("apcore_a2a.serve") as mock_serve: + with patch("apcore.discovery.Registry") as mock_registry_cls, patch("apcore_a2a.serve") as mock_serve: mock_reg = MagicMock() mock_reg.list.return_value = ["my.module"] mock_registry_cls.return_value = mock_reg @@ -287,7 +297,7 @@ def test_serve_runtime_error_exits_2(tmp_path, capsys): log_level="info", ) - with patch("apcore.Registry") as mock_registry_cls, patch("apcore_a2a.serve") as mock_serve: + with patch("apcore.discovery.Registry") as mock_registry_cls, patch("apcore_a2a.serve") as mock_serve: mock_reg = MagicMock() mock_reg.list.return_value = ["my.module"] mock_registry_cls.return_value = mock_reg @@ -325,7 +335,7 @@ def test_serve_keyboard_interrupt_exits_0(tmp_path): log_level="info", ) - with patch("apcore.Registry") as mock_registry_cls, patch("apcore_a2a.serve") as mock_serve: + with patch("apcore.discovery.Registry") as mock_registry_cls, patch("apcore_a2a.serve") as mock_serve: mock_reg = MagicMock() mock_reg.list.return_value = ["my.module"] mock_registry_cls.return_value = mock_reg @@ -365,7 +375,7 @@ def test_serve_calls_serve_with_correct_args(tmp_path): log_level="debug", ) - with patch("apcore.Registry") as mock_registry_cls, patch("apcore_a2a.serve") as mock_serve: + with patch("apcore.discovery.Registry") as mock_registry_cls, patch("apcore_a2a.serve") as mock_serve: mock_reg = MagicMock() mock_reg.list.return_value = ["my.module", "other.module"] mock_registry_cls.return_value = mock_reg @@ -417,7 +427,7 @@ def test_serve_default_url_constructed_from_host_port(tmp_path): log_level="info", ) - with patch("apcore.Registry") as mock_registry_cls, patch("apcore_a2a.serve") as mock_serve: + with patch("apcore.discovery.Registry") as mock_registry_cls, patch("apcore_a2a.serve") as mock_serve: mock_reg = MagicMock() mock_reg.list.return_value = ["my.module"] mock_registry_cls.return_value = mock_reg diff --git a/a2a/rust/Cargo.lock b/a2a/rust/Cargo.lock index ee5153aa..68b227b3 100644 --- a/a2a/rust/Cargo.lock +++ b/a2a/rust/Cargo.lock @@ -92,9 +92,9 @@ dependencies = [ [[package]] name = "apcore" -version = "1.0.0-alpha.1" +version = "1.0.0-alpha.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bbc1db3680f3d81b7096fa5eb70476a2c043b333681c2a7bba3597a49bbf11f6" +checksum = "54e630a6f3c82ee9e01aec1f58ad14a06e21d8082414a1f4d398bce2f45b4de3" dependencies = [ "async-stream", "async-trait", @@ -120,7 +120,7 @@ dependencies = [ [[package]] name = "apcore-a2a" -version = "0.8.7-alpha.1" +version = "0.8.7-alpha.2" dependencies = [ "apcore", "apcore-toolkit", @@ -153,9 +153,9 @@ dependencies = [ [[package]] name = "apcore-toolkit" -version = "0.15.1-alpha.1" +version = "0.15.1-alpha.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7054dcf35f7f9f0823f3118f3ab531a511cca25d6c2f07cdc7c222de10bf0673" +checksum = "8c073619a002dcf93c6391a22c537420b86f3863dd3eef7b6cc9ebbec712c146" dependencies = [ "apcore", "async-trait", diff --git a/a2a/rust/Cargo.toml b/a2a/rust/Cargo.toml index aecd1c36..fb56bd2d 100644 --- a/a2a/rust/Cargo.toml +++ b/a2a/rust/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "apcore-a2a" -version = "0.8.7-alpha.1" +version = "0.8.7-alpha.2" edition = "2021" rust-version = "1.86" description = "A2A protocol adapter for apcore — expose apcore modules as A2A agents" @@ -27,12 +27,12 @@ default = [] openapi = ["apcore-toolkit/http-proxy"] [dependencies] -apcore = ">=0.33.0, <=1.0.0-alpha.1" +apcore = { version = "=1.0.0-alpha.2", default-features = false, features = ["discovery", "sys-modules"] } # `default-features = false` so `http-proxy` — a *default* feature of the # toolkit — is reached through this crate's `openapi` feature instead of being # enabled unconditionally. The unconditional import (`deep_resolve_refs`) is # outside that feature. -apcore-toolkit = { version = "=0.15.1-alpha.1", default-features = false } +apcore-toolkit = { version = "=0.15.1-alpha.2", default-features = false } tokio = { version = "1", features = ["full"] } serde = { version = "1", features = ["derive"] } serde_json = "1" diff --git a/a2a/rust/tests/integration.rs b/a2a/rust/tests/integration.rs index f8e3ef62..90bf14f1 100644 --- a/a2a/rust/tests/integration.rs +++ b/a2a/rust/tests/integration.rs @@ -1620,14 +1620,11 @@ async fn extended_card_keeps_the_system_namespace() { #[tokio::test] async fn an_unprotected_control_surface_warns_without_refusing_to_start() { - // srs FR-AGC-007 criteria 1, 2 and 4: the message is emitted, the server - // still starts, and neither card changes. - // - // The condition is real: `system.control.*` declares `requires_approval`, - // but apcore's approval gate warns once and continues when no - // `ApprovalHandler` is configured, so withholding the namespace from the - // card removes it from discovery and not from dispatch. - let (_registry, executor) = system_namespace_executor(None); + // srs FR-AGC-007 criteria 1, 2 and 4: the server warns and still starts. + // The explicit non-strict policy leaves approval-required control modules + // callable without a handler while the public card omits the namespace. + let (_registry, mut executor) = system_namespace_executor(None); + executor.set_policy(Some(apcore::ExecutionPolicy::default().with_strict(false))); assert!( executor.governance_state().unprotected_control_surface, "precondition: control modules registered with no gate engaging" diff --git a/a2a/typescript/package.json b/a2a/typescript/package.json index fe4963e8..a1c229bf 100644 --- a/a2a/typescript/package.json +++ b/a2a/typescript/package.json @@ -1,6 +1,6 @@ { "name": "apcore-a2a", - "version": "0.8.9-alpha.1", + "version": "0.8.9-alpha.2", "packageManager": "pnpm@10.30.1", "description": "Automatic A2A Protocol Adapter for apcore Module Registry", "type": "module", @@ -33,8 +33,8 @@ }, "dependencies": { "@a2a-js/sdk": ">=1.0.1", - "apcore-js": ">=0.33.0 <1.0.0 || 1.0.0-alpha.1", - "apcore-toolkit": "0.15.1-alpha.1", + "apcore-js": "1.0.0-alpha.2", + "apcore-toolkit": "0.15.1-alpha.2", "express": "^5.1.0", "jsonwebtoken": "^9.0.3", "uuid": "^13.0.2" diff --git a/a2a/typescript/pnpm-lock.yaml b/a2a/typescript/pnpm-lock.yaml index 8856574a..e933ee26 100644 --- a/a2a/typescript/pnpm-lock.yaml +++ b/a2a/typescript/pnpm-lock.yaml @@ -12,11 +12,11 @@ importers: specifier: '>=1.0.1' version: 1.0.1(express@5.2.1) apcore-js: - specifier: '>=0.33.0 <1.0.0 || 1.0.0-alpha.1' - version: 0.33.0 + specifier: 1.0.0-alpha.2 + version: 1.0.0-alpha.2(typescript@5.9.3) apcore-toolkit: - specifier: 0.15.1-alpha.1 - version: 0.15.1-alpha.1(@sinclair/typebox@0.34.48) + specifier: 0.15.1-alpha.2 + version: 0.15.1-alpha.2(@sinclair/typebox@0.34.48)(typescript@5.9.3) express: specifier: ^5.1.0 version: 5.2.1 @@ -656,12 +656,17 @@ packages: ajv@8.20.0: resolution: {integrity: sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==} - apcore-js@0.33.0: - resolution: {integrity: sha512-+0UPovkB37qKy9kUwZmgSK6an+RqOUy+XOU9sEAauXStmQYIWmPBV7ACymQ9nwPI4RVAKiWbU4upMIqrCitxoQ==} + apcore-js@1.0.0-alpha.2: + resolution: {integrity: sha512-WnQj/V/f43e0PbYIALpvjrerv/XOJStKE+FuOEl80qYEAtKWb/pKn1ho7p11HBinc6diCBxqIGScoN7qscnsbg==} engines: {node: '>=20.0.0'} + peerDependencies: + typescript: ^5.5.0 + peerDependenciesMeta: + typescript: + optional: true - apcore-toolkit@0.15.1-alpha.1: - resolution: {integrity: sha512-e8E9gtYAKLeBkpdIQisey4LogMdTR+qffL5PD5U0TyLiVl2v90xSBVXfHof3FkJWMj0/MKRqjlyzBk750xmt+w==} + apcore-toolkit@0.15.1-alpha.2: + resolution: {integrity: sha512-nBMk99wAGjSH/E3fCj4I5FsvlvYiVs+k+ARIGc6u+kkxiTvxoAlQNKAUviBYJBrmItwDVl+9EonaEO2qfiRQGg==} engines: {node: '>=20.10.0'} peerDependencies: '@sinclair/typebox': '>=0.31.0' @@ -1946,18 +1951,22 @@ snapshots: json-schema-traverse: 1.0.0 require-from-string: 2.0.2 - apcore-js@0.33.0: + apcore-js@1.0.0-alpha.2(typescript@5.9.3): dependencies: '@sinclair/typebox': 0.34.48 js-yaml: 4.3.2 uuid: 11.1.1 + optionalDependencies: + typescript: 5.9.3 - apcore-toolkit@0.15.1-alpha.1(@sinclair/typebox@0.34.48): + apcore-toolkit@0.15.1-alpha.2(@sinclair/typebox@0.34.48)(typescript@5.9.3): dependencies: '@sinclair/typebox': 0.34.48 ajv: 8.20.0 - apcore-js: 0.33.0 + apcore-js: 1.0.0-alpha.2(typescript@5.9.3) js-yaml: 4.3.2 + transitivePeerDependencies: + - typescript apdev-js@0.2.0(typescript@5.9.3): dependencies: diff --git a/a2a/typescript/src/cli.ts b/a2a/typescript/src/cli.ts index ed5f3a35..80e24891 100644 --- a/a2a/typescript/src/cli.ts +++ b/a2a/typescript/src/cli.ts @@ -361,7 +361,7 @@ async function runServe(values: CliValues): Promise { ); } - const { Registry } = await import("apcore-js"); + const { Registry } = await import("apcore-js/full"); let registry: ApcoreRegistry; if (extensionsDir) { diff --git a/a2a/typescript/src/config.ts b/a2a/typescript/src/config.ts index 245daffa..2e2d0e0d 100644 --- a/a2a/typescript/src/config.ts +++ b/a2a/typescript/src/config.ts @@ -14,7 +14,7 @@ * at import time rather than being ignored. */ -import { Config } from "apcore-js"; +import { Config } from "apcore-js/config"; export const A2A_NAMESPACE = "apcore-a2a"; export const A2A_ENV_PREFIX = "APCORE_A2A"; diff --git a/a2a/typescript/src/openapi-backend.ts b/a2a/typescript/src/openapi-backend.ts index 94b36d0a..27e23aa6 100644 --- a/a2a/typescript/src/openapi-backend.ts +++ b/a2a/typescript/src/openapi-backend.ts @@ -31,7 +31,8 @@ */ import path from "node:path"; -import { Config, Registry } from "apcore-js"; +import { Registry } from "apcore-js"; +import { Config } from "apcore-js/config"; import { HTTPProxyRegistryWriter, OpenAPIScanner, diff --git a/a2a/typescript/src/serve.ts b/a2a/typescript/src/serve.ts index 7d1a0bb5..d78c70c1 100644 --- a/a2a/typescript/src/serve.ts +++ b/a2a/typescript/src/serve.ts @@ -1,6 +1,6 @@ import http from "node:http"; import type { Express } from "express"; -import { Config } from "apcore-js"; +import { Config } from "apcore-js/config"; import { A2AServerFactory } from "./server/factory.js"; import type { Registry } from "./adapters/agent-card.js"; import type { Authenticator } from "./auth/types.js"; diff --git a/a2a/typescript/src/server/factory.ts b/a2a/typescript/src/server/factory.ts index 1bcbdeef..bfc8c01c 100644 --- a/a2a/typescript/src/server/factory.ts +++ b/a2a/typescript/src/server/factory.ts @@ -8,14 +8,11 @@ import { } from "@a2a-js/sdk/server"; import { jsonRpcHandler, agentCardHandler, restHandler } from "@a2a-js/sdk/server/express"; -import { - Config, - ErrorFormatterRegistry, - ObsLoggingMiddleware, - ErrorHistoryMiddleware, - ErrorHistory, - registerSysModules, -} from "apcore-js"; +import { ErrorFormatterRegistry, ErrorHistoryMiddleware } from "apcore-js"; +import { Config } from "apcore-js/config"; +import { ErrorHistory } from "apcore-js/full"; +import { ObsLoggingMiddleware } from "apcore-js/observability"; +import { registerSysModules } from "apcore-js/sys-modules"; import { registerA2aNamespace } from "../config.js"; diff --git a/a2a/typescript/tests/server/system-modules.test.ts b/a2a/typescript/tests/server/system-modules.test.ts index d0941fdb..2d76d9f8 100644 --- a/a2a/typescript/tests/server/system-modules.test.ts +++ b/a2a/typescript/tests/server/system-modules.test.ts @@ -12,7 +12,9 @@ * without an `acl/` directory has no ACL at all. */ import { describe, it, expect, vi, afterEach } from "vitest"; -import { Registry, Executor, Config, registerSysModules, module as apcoreModule } from "apcore-js"; +import { Registry, Executor, module as apcoreModule } from "apcore-js"; +import { Config } from "apcore-js/config"; +import { registerSysModules } from "apcore-js/sys-modules"; import { Type } from "@sinclair/typebox"; import { A2AServerFactory } from "../../src/server/factory.js"; diff --git a/cli/README.md b/cli/README.md index d92f4192..7daf808b 100644 --- a/cli/README.md +++ b/cli/README.md @@ -533,8 +533,6 @@ apcore-cli uses a 4-tier configuration precedence: ```yaml extensions: root: ./extensions -logging: - level: DEBUG sandbox: enabled: false cli: diff --git a/cli/python/README.md b/cli/python/README.md index 67ebb348..63a1566e 100644 --- a/cli/python/README.md +++ b/cli/python/README.md @@ -453,8 +453,6 @@ apcore-cli uses a 4-tier configuration precedence: ```yaml extensions: root: ./extensions -logging: - level: DEBUG sandbox: enabled: false cli: diff --git a/cli/python/pyproject.toml b/cli/python/pyproject.toml index 58ce7567..5b3dabb6 100644 --- a/cli/python/pyproject.toml +++ b/cli/python/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "hatchling.build" [project] name = "apcore-cli" -version = "0.14.2a1" +version = "0.14.2a2" description = "Terminal adapter for apcore — execute AI-Perceivable modules from the command line" readme = "README.md" license = "Apache-2.0" @@ -26,8 +26,8 @@ classifiers = [ "Environment :: Console", ] dependencies = [ - "apcore>=0.33.0,<=1.0.0a1", - "apcore-toolkit[http-proxy]==0.15.1a1", + "apcore[config,discovery]==1.0.0a2", + "apcore-toolkit[http-proxy]==0.15.1a2", "click>=8.1", "jsonschema>=4.20", "rich>=13.0", diff --git a/cli/python/src/apcore_cli/_sandbox_runner.py b/cli/python/src/apcore_cli/_sandbox_runner.py index 549c58e3..be9eaa35 100644 --- a/cli/python/src/apcore_cli/_sandbox_runner.py +++ b/cli/python/src/apcore_cli/_sandbox_runner.py @@ -25,7 +25,8 @@ def main() -> None: input_data = json.loads(sys.stdin.read()) extensions_root = os.environ.get("APCORE_EXTENSIONS_ROOT", "./extensions") - from apcore import Executor, Registry + from apcore.discovery import Registry + from apcore.executor import Executor registry = Registry(extensions_dir=extensions_root) registry.discover() diff --git a/cli/python/src/apcore_cli/acl_loader.py b/cli/python/src/apcore_cli/acl_loader.py index 66e4aa8b..4ab24ee7 100644 --- a/cli/python/src/apcore_cli/acl_loader.py +++ b/cli/python/src/apcore_cli/acl_loader.py @@ -25,7 +25,8 @@ from apcore_cli.security.audit import get_audit_logger if TYPE_CHECKING: # pragma: no cover - typing only - from apcore import ACL, AuditEntry, Context, Identity + from apcore.acl import ACL, AuditEntry + from apcore.context import Context, Identity from apcore_cli.config import ConfigResolver @@ -234,7 +235,7 @@ def load_cli_acl(root: str, *, audit_enabled: bool = True, include_denied: bool unknown rule key, malformed pattern array, non-mapping ``conditions``). Both map to exit ``47``. """ - from apcore import ACL as _ACL + from apcore.acl import ACL as _ACL acl_file = acl_file_for_root(root) if acl_file is None: diff --git a/cli/python/src/apcore_cli/config.py b/cli/python/src/apcore_cli/config.py index eecd6bf9..158d2e34 100644 --- a/cli/python/src/apcore_cli/config.py +++ b/cli/python/src/apcore_cli/config.py @@ -34,7 +34,7 @@ def register_config_namespace() -> bool: install error, not a silent no-op. The prior graceful-fallback path was removed in the 6.2 fix. """ - from apcore import Config + from apcore.config import Config Config.register_namespace( name="apcore-cli", diff --git a/cli/python/src/apcore_cli/factory.py b/cli/python/src/apcore_cli/factory.py index de4dcae4..c135ac06 100644 --- a/cli/python/src/apcore_cli/factory.py +++ b/cli/python/src/apcore_cli/factory.py @@ -274,7 +274,7 @@ def create_cli( if _skip_discovery: # Skip filesystem discovery entirely. try: - from apcore import Executor as _Executor + from apcore.executor import Executor as _Executor if executor is None: executor = _Executor(registry) @@ -313,7 +313,7 @@ def create_cli( logger.warning("Discovery failed: %s", e) try: - from apcore import Executor as _Executor + from apcore.executor import Executor as _Executor if executor is None: executor = _Executor(registry) @@ -340,8 +340,8 @@ def create_cli( exit_with(EXIT_CONFIG_NOT_FOUND) try: - from apcore import Executor as _Executor - from apcore import Registry as _Registry + from apcore.executor import Executor as _Executor + from apcore.full import Registry as _Registry registry = _Registry(extensions_dir=ext_dir) try: diff --git a/cli/python/src/apcore_cli/system_cmd.py b/cli/python/src/apcore_cli/system_cmd.py index cee7f0f9..ac38d45f 100644 --- a/cli/python/src/apcore_cli/system_cmd.py +++ b/cli/python/src/apcore_cli/system_cmd.py @@ -433,7 +433,7 @@ def config_group() -> None: def config_get_cmd(key: str) -> None: """Read a configuration value by dot-path key.""" try: - from apcore import Config + from apcore.config import Config value = Config().get(key) click.echo(f"{key} = {value!r}") diff --git a/cli/python/tests/test_e2e.py b/cli/python/tests/test_e2e.py index 3ba9e65f..07aaa773 100644 --- a/cli/python/tests/test_e2e.py +++ b/cli/python/tests/test_e2e.py @@ -316,20 +316,16 @@ def test_approval_required_blocked_in_non_tty(self, real_cli): result.stderr if hasattr(result, "stderr") else "" ) - def test_approval_bypassed_with_yes(self, real_cli): + def test_yes_does_not_replace_a_core_approval_handler(self, real_cli): runner = CliRunner() result = runner.invoke(real_cli, ["admin.dangerous", "--target", "my-data", "--yes"]) - assert result.exit_code == 0 - data = json.loads(result.output) - assert data["deleted"] == "my-data" + assert result.exit_code == 46 - def test_approval_bypassed_with_env_var(self, real_cli, monkeypatch): + def test_env_var_does_not_replace_a_core_approval_handler(self, real_cli, monkeypatch): monkeypatch.setenv("APCORE_CLI_AUTO_APPROVE", "1") runner = CliRunner() result = runner.invoke(real_cli, ["admin.dangerous", "--target", "my-data"]) - assert result.exit_code == 0 - data = json.loads(result.output) - assert data["deleted"] == "my-data" + assert result.exit_code == 46 def test_no_approval_normal_module(self, real_cli): runner = CliRunner() diff --git a/cli/python/tests/test_sandbox_runner.py b/cli/python/tests/test_sandbox_runner.py index b8f1909e..7f209e6a 100644 --- a/cli/python/tests/test_sandbox_runner.py +++ b/cli/python/tests/test_sandbox_runner.py @@ -24,8 +24,8 @@ def _invoke_main(module_id: str, stdin_json: str, extra_env: dict | None = None) patch("sys.stdin", io.StringIO(stdin_json)), patch("sys.stdout", captured), patch.dict("os.environ", env_override, clear=False), - patch("apcore.Registry", return_value=mock_registry), - patch("apcore.Executor", return_value=mock_executor), + patch("apcore.discovery.Registry", return_value=mock_registry), + patch("apcore.executor.Executor", return_value=mock_executor), ): main() return captured.getvalue() @@ -43,8 +43,8 @@ def test_calls_executor_with_parsed_input(self): patch.object(sys, "argv", ["runner", "math.add"]), patch("sys.stdin", io.StringIO('{"a": 1}')), patch("sys.stdout", captured), - patch("apcore.Registry", return_value=mock_registry), - patch("apcore.Executor", return_value=mock_executor), + patch("apcore.discovery.Registry", return_value=mock_registry), + patch("apcore.executor.Executor", return_value=mock_executor), ): from apcore_cli._sandbox_runner import main @@ -66,8 +66,8 @@ def test_extensions_root_from_env_used_for_registry(self): patch("sys.stdin", io.StringIO("{}")), patch("sys.stdout", io.StringIO()), patch.dict("os.environ", {"APCORE_EXTENSIONS_ROOT": "/abs/ext"}, clear=False), - patch("apcore.Registry", registry_cls), - patch("apcore.Executor", return_value=mock_executor), + patch("apcore.discovery.Registry", registry_cls), + patch("apcore.executor.Executor", return_value=mock_executor), ): from apcore_cli._sandbox_runner import main @@ -86,8 +86,8 @@ def test_empty_input_object_accepted(self): patch.object(sys, "argv", ["runner", "mod.id"]), patch("sys.stdin", io.StringIO("{}")), patch("sys.stdout", captured), - patch("apcore.Registry", return_value=mock_registry), - patch("apcore.Executor", return_value=mock_executor), + patch("apcore.discovery.Registry", return_value=mock_registry), + patch("apcore.executor.Executor", return_value=mock_executor), ): from apcore_cli._sandbox_runner import main diff --git a/cli/python/tests/test_system_cmd.py b/cli/python/tests/test_system_cmd.py index ec4de0ab..8aac926c 100644 --- a/cli/python/tests/test_system_cmd.py +++ b/cli/python/tests/test_system_cmd.py @@ -329,17 +329,10 @@ def test_config_get_success(self, monkeypatch): fake_config_cls = MagicMock() fake_config_cls.return_value.get.return_value = "42" monkeypatch.setattr( - "apcore.Config", + "apcore.config.Config", fake_config_cls, raising=False, ) - # Guard: patch inside the lazy-imported reference too. - import sys - - apcore_mod = sys.modules.get("apcore") - if apcore_mod is not None: - monkeypatch.setattr(apcore_mod, "Config", fake_config_cls, raising=False) - ex = _make_executor() cli = _build_apcli_with(register_config_command, ex) result = CliRunner().invoke(cli, ["config", "get", "some.key"]) @@ -352,12 +345,7 @@ def test_config_get_error_path(self, monkeypatch): """Exception during Config().get propagates to exit 1.""" bad_config = MagicMock() bad_config.return_value.get.side_effect = RuntimeError("nope") - import sys - - apcore_mod = sys.modules.get("apcore") - if apcore_mod is not None: - monkeypatch.setattr(apcore_mod, "Config", bad_config, raising=False) - monkeypatch.setattr("apcore.Config", bad_config, raising=False) + monkeypatch.setattr("apcore.config.Config", bad_config, raising=False) ex = _make_executor() cli = _build_apcli_with(register_config_command, ex) diff --git a/cli/rust/Cargo.lock b/cli/rust/Cargo.lock index 88ca6d2e..f348eb91 100644 --- a/cli/rust/Cargo.lock +++ b/cli/rust/Cargo.lock @@ -133,9 +133,9 @@ checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" [[package]] name = "apcore" -version = "1.0.0-alpha.1" +version = "1.0.0-alpha.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bbc1db3680f3d81b7096fa5eb70476a2c043b333681c2a7bba3597a49bbf11f6" +checksum = "54e630a6f3c82ee9e01aec1f58ad14a06e21d8082414a1f4d398bce2f45b4de3" dependencies = [ "async-stream", "async-trait", @@ -144,7 +144,6 @@ dependencies = [ "futures-core", "futures-util", "jsonschema", - "notify", "parking_lot", "referencing", "regex", @@ -161,7 +160,7 @@ dependencies = [ [[package]] name = "apcore-cli" -version = "0.14.2-alpha.1" +version = "0.14.2-alpha.2" dependencies = [ "aes-gcm", "anyhow", @@ -197,9 +196,9 @@ dependencies = [ [[package]] name = "apcore-toolkit" -version = "0.15.1-alpha.1" +version = "0.15.1-alpha.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7054dcf35f7f9f0823f3118f3ab531a511cca25d6c2f07cdc7c222de10bf0673" +checksum = "8c073619a002dcf93c6391a22c537420b86f3863dd3eef7b6cc9ebbec712c146" dependencies = [ "apcore", "async-trait", @@ -1053,15 +1052,6 @@ dependencies = [ "num", ] -[[package]] -name = "fsevent-sys" -version = "4.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "76ee7a02da4d231650c7cea31349b889be2f45ddb3ef3032d2ec8185f6313fd2" -dependencies = [ - "libc", -] - [[package]] name = "futures-channel" version = "0.3.32" @@ -1566,26 +1556,6 @@ dependencies = [ "serde_core", ] -[[package]] -name = "inotify" -version = "0.11.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bd5b3eaf1a28b758ac0faa5a4254e8ab2705605496f1b1f3fbbc3988ad73d199" -dependencies = [ - "bitflags 2.11.0", - "inotify-sys", - "libc", -] - -[[package]] -name = "inotify-sys" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e05c02b5e89bff3b946cedeca278abc628fe811e604f027c45a8aa3cf793d0eb" -dependencies = [ - "libc", -] - [[package]] name = "inout" version = "0.1.4" @@ -1695,26 +1665,6 @@ dependencies = [ "windows-sys 0.52.0", ] -[[package]] -name = "kqueue" -version = "1.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eac30106d7dce88daf4a3fcb4879ea939476d5074a9b7ddd0fb97fa4bed5596a" -dependencies = [ - "kqueue-sys", - "libc", -] - -[[package]] -name = "kqueue-sys" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a7b65860415f949f23fa882e669f2dbd4a0f0eeb1acdd56790b30494afd7da2f" -dependencies = [ - "bitflags 2.11.0", - "libc", -] - [[package]] name = "lazy_static" version = "1.5.0" @@ -1853,7 +1803,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "50b7e5b27aa02a74bac8c3f23f448f8d87ff11f92d3aac1a6ed369ee08cc56c1" dependencies = [ "libc", - "log", "wasi", "windows-sys 0.61.2", ] @@ -1899,33 +1848,6 @@ dependencies = [ "libc", ] -[[package]] -name = "notify" -version = "8.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4d3d07927151ff8575b7087f245456e549fea62edf0ec4e565a5ee50c8402bc3" -dependencies = [ - "bitflags 2.11.0", - "fsevent-sys", - "inotify", - "kqueue", - "libc", - "log", - "mio", - "notify-types", - "walkdir", - "windows-sys 0.60.2", -] - -[[package]] -name = "notify-types" -version = "2.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "42b8cfee0e339a0337359f3c88165702ac6e600dc01c0cc9579a92d62b08477a" -dependencies = [ - "bitflags 2.11.0", -] - [[package]] name = "nu-ansi-term" version = "0.50.3" @@ -3674,15 +3596,6 @@ dependencies = [ "windows-targets 0.52.6", ] -[[package]] -name = "windows-sys" -version = "0.60.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb" -dependencies = [ - "windows-targets 0.53.5", -] - [[package]] name = "windows-sys" version = "0.61.2" @@ -3716,30 +3629,13 @@ dependencies = [ "windows_aarch64_gnullvm 0.52.6", "windows_aarch64_msvc 0.52.6", "windows_i686_gnu 0.52.6", - "windows_i686_gnullvm 0.52.6", + "windows_i686_gnullvm", "windows_i686_msvc 0.52.6", "windows_x86_64_gnu 0.52.6", "windows_x86_64_gnullvm 0.52.6", "windows_x86_64_msvc 0.52.6", ] -[[package]] -name = "windows-targets" -version = "0.53.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4945f9f551b88e0d65f3db0bc25c33b8acea4d9e41163edf90dcd0b19f9069f3" -dependencies = [ - "windows-link", - "windows_aarch64_gnullvm 0.53.1", - "windows_aarch64_msvc 0.53.1", - "windows_i686_gnu 0.53.1", - "windows_i686_gnullvm 0.53.1", - "windows_i686_msvc 0.53.1", - "windows_x86_64_gnu 0.53.1", - "windows_x86_64_gnullvm 0.53.1", - "windows_x86_64_msvc 0.53.1", -] - [[package]] name = "windows_aarch64_gnullvm" version = "0.48.5" @@ -3752,12 +3648,6 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" -[[package]] -name = "windows_aarch64_gnullvm" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a9d8416fa8b42f5c947f8482c43e7d89e73a173cead56d044f6a56104a6d1b53" - [[package]] name = "windows_aarch64_msvc" version = "0.48.5" @@ -3770,12 +3660,6 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" -[[package]] -name = "windows_aarch64_msvc" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b9d782e804c2f632e395708e99a94275910eb9100b2114651e04744e9b125006" - [[package]] name = "windows_i686_gnu" version = "0.48.5" @@ -3788,24 +3672,12 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" -[[package]] -name = "windows_i686_gnu" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "960e6da069d81e09becb0ca57a65220ddff016ff2d6af6a223cf372a506593a3" - [[package]] name = "windows_i686_gnullvm" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" -[[package]] -name = "windows_i686_gnullvm" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fa7359d10048f68ab8b09fa71c3daccfb0e9b559aed648a8f95469c27057180c" - [[package]] name = "windows_i686_msvc" version = "0.48.5" @@ -3818,12 +3690,6 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" -[[package]] -name = "windows_i686_msvc" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e7ac75179f18232fe9c285163565a57ef8d3c89254a30685b57d83a38d326c2" - [[package]] name = "windows_x86_64_gnu" version = "0.48.5" @@ -3836,12 +3702,6 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" -[[package]] -name = "windows_x86_64_gnu" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c3842cdd74a865a8066ab39c8a7a473c0778a3f29370b5fd6b4b9aa7df4a499" - [[package]] name = "windows_x86_64_gnullvm" version = "0.48.5" @@ -3854,12 +3714,6 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" -[[package]] -name = "windows_x86_64_gnullvm" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0ffa179e2d07eee8ad8f57493436566c7cc30ac536a3379fdf008f47f6bb7ae1" - [[package]] name = "windows_x86_64_msvc" version = "0.48.5" @@ -3872,12 +3726,6 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" -[[package]] -name = "windows_x86_64_msvc" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650" - [[package]] name = "winnow" version = "0.5.40" diff --git a/cli/rust/Cargo.toml b/cli/rust/Cargo.toml index 7c2a5854..da15075b 100644 --- a/cli/rust/Cargo.toml +++ b/cli/rust/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "apcore-cli" -version = "0.14.2-alpha.1" +version = "0.14.2-alpha.2" edition = "2021" description = "Command-line interface for apcore modules" license = "Apache-2.0" @@ -21,7 +21,7 @@ name = "apcore_cli" path = "src/lib.rs" [dependencies] -apcore = "=1.0.0-alpha.1" +apcore = { version = "=1.0.0-alpha.2", default-features = false, features = ["config"] } async-trait = "0.1" clap = { version = "4", features = ["derive", "env", "string"] } serde = { version = "1", features = ["derive"] } @@ -48,7 +48,7 @@ chrono = { version = "0.4", features = ["serde"] } tempfile = "3" nix = { version = "0.30", features = ["user"] } libc = "0.2" -apcore-toolkit = { version = "=0.15.1-alpha.1", features = ["http-proxy"] } +apcore-toolkit = { version = "=0.15.1-alpha.2", features = ["http-proxy"] } [features] # ADR-07 is fully landed as of 0.10.0 (6.2 fix): apcore-toolkit is a hard diff --git a/cli/typescript/package.json b/cli/typescript/package.json index e4e3396d..51e8aeeb 100644 --- a/cli/typescript/package.json +++ b/cli/typescript/package.json @@ -1,6 +1,6 @@ { "name": "apcore-cli", - "version": "0.14.2-alpha.1", + "version": "0.14.2-alpha.2", "description": "CLI wrapper for the apcore core SDK — exposes apcore modules as CLI commands", "type": "module", "main": "./dist/index.js", @@ -30,8 +30,8 @@ "node": ">=20.0.0" }, "peerDependencies": { - "apcore-js": ">=0.33.0 <1.0.0 || 1.0.0-alpha.1", - "apcore-toolkit": "0.15.1-alpha.1" + "apcore-js": "1.0.0-alpha.2", + "apcore-toolkit": "0.15.1-alpha.2" }, "dependencies": { "@sinclair/typebox": "^0.34.0", @@ -47,8 +47,8 @@ "@typescript-eslint/eslint-plugin": "^8.59.0", "@typescript-eslint/parser": "^8.59.0", "@vitest/coverage-v8": "^5.1.0", - "apcore-js": "^0.33.0 || 1.0.0-alpha.1", - "apcore-toolkit": "0.15.1-alpha.1", + "apcore-js": "1.0.0-alpha.2", + "apcore-toolkit": "0.15.1-alpha.2", "apdev-js": "^0.2.4", "eslint": "^10.2.1", "tsup": "^8.0.0", diff --git a/cli/typescript/pnpm-lock.yaml b/cli/typescript/pnpm-lock.yaml index 0141cb2b..4286b510 100644 --- a/cli/typescript/pnpm-lock.yaml +++ b/cli/typescript/pnpm-lock.yaml @@ -34,11 +34,11 @@ importers: specifier: ^5.1.0 version: 5.1.0(vitest@5.1.0) apcore-js: - specifier: ^0.33.0 || 1.0.0-alpha.1 - version: 0.33.0 + specifier: 1.0.0-alpha.2 + version: 1.0.0-alpha.2(typescript@5.9.3) apcore-toolkit: - specifier: 0.15.1-alpha.1 - version: 0.15.1-alpha.1(@sinclair/typebox@0.34.48) + specifier: 0.15.1-alpha.2 + version: 0.15.1-alpha.2(@sinclair/typebox@0.34.48)(typescript@5.9.3) apdev-js: specifier: ^0.2.4 version: 0.2.4(typescript@5.9.3) @@ -731,12 +731,17 @@ packages: any-promise@1.3.0: resolution: {integrity: sha512-7UvmKalWRt1wgjL1RrGxoSJW/0QZFIegpeGvZG9kjp8vrRu55XTHbwnqq2GpXm9uLbcuhxm3IqX9OB4MZR1b2A==} - apcore-js@0.33.0: - resolution: {integrity: sha512-+0UPovkB37qKy9kUwZmgSK6an+RqOUy+XOU9sEAauXStmQYIWmPBV7ACymQ9nwPI4RVAKiWbU4upMIqrCitxoQ==} + apcore-js@1.0.0-alpha.2: + resolution: {integrity: sha512-WnQj/V/f43e0PbYIALpvjrerv/XOJStKE+FuOEl80qYEAtKWb/pKn1ho7p11HBinc6diCBxqIGScoN7qscnsbg==} engines: {node: '>=20.0.0'} + peerDependencies: + typescript: ^5.5.0 + peerDependenciesMeta: + typescript: + optional: true - apcore-toolkit@0.15.1-alpha.1: - resolution: {integrity: sha512-e8E9gtYAKLeBkpdIQisey4LogMdTR+qffL5PD5U0TyLiVl2v90xSBVXfHof3FkJWMj0/MKRqjlyzBk750xmt+w==} + apcore-toolkit@0.15.1-alpha.2: + resolution: {integrity: sha512-nBMk99wAGjSH/E3fCj4I5FsvlvYiVs+k+ARIGc6u+kkxiTvxoAlQNKAUviBYJBrmItwDVl+9EonaEO2qfiRQGg==} engines: {node: '>=20.10.0'} peerDependencies: '@sinclair/typebox': '>=0.31.0' @@ -1939,18 +1944,22 @@ snapshots: any-promise@1.3.0: {} - apcore-js@0.33.0: + apcore-js@1.0.0-alpha.2(typescript@5.9.3): dependencies: '@sinclair/typebox': 0.34.48 js-yaml: 4.3.2 uuid: 11.1.1 + optionalDependencies: + typescript: 5.9.3 - apcore-toolkit@0.15.1-alpha.1(@sinclair/typebox@0.34.48): + apcore-toolkit@0.15.1-alpha.2(@sinclair/typebox@0.34.48)(typescript@5.9.3): dependencies: '@sinclair/typebox': 0.34.48 ajv: 8.20.0 - apcore-js: 0.33.0 + apcore-js: 1.0.0-alpha.2(typescript@5.9.3) js-yaml: 4.3.2 + transitivePeerDependencies: + - typescript apdev-js@0.2.4(typescript@5.9.3): dependencies: diff --git a/cli/typescript/src/acl-loader.ts b/cli/typescript/src/acl-loader.ts index ec8135a9..cd248e09 100644 --- a/cli/typescript/src/acl-loader.ts +++ b/cli/typescript/src/acl-loader.ts @@ -16,7 +16,8 @@ import * as fs from "node:fs"; import * as path from "node:path"; -import { ACL, ACLDeniedError, Context, createIdentity } from "apcore-js"; +import { ACLDeniedError, Context, createIdentity } from "apcore-js"; +import { ACL } from "apcore-js/full"; import type { AuditEntry, AuditLogger as AclAuditCallback } from "apcore-js"; import { ConfigResolver, DEFAULTS } from "./config.js"; import { EXIT_CODES } from "./errors.js"; diff --git a/cli/typescript/src/config.ts b/cli/typescript/src/config.ts index 3a3080b6..a75ded22 100644 --- a/cli/typescript/src/config.ts +++ b/cli/typescript/src/config.ts @@ -5,7 +5,7 @@ */ import * as fs from "node:fs"; -import { createRequire } from "node:module"; +import { Config } from "apcore-js/config"; import yaml from "js-yaml"; import { warn as logWarn } from "./logger.js"; @@ -97,26 +97,17 @@ const LEGACY_TO_NAMESPACE: Record = Object.fromEntries( ); /** - * Register the apcore-cli Config Bus namespace (apcore >= 0.15.0). - * Safe to call even when apcore-js is unavailable or < 0.15.0. + * Register the apcore-cli Config Bus namespace. */ export function registerConfigNamespace(): void { try { - // Use createRequire to load apcore-js from an ESM module without relying on - // tsup's `shims` option (which injects a `require` into the bundled output - // but not into vitest/tsx dev paths). Native `require()` at module scope is - // a ReferenceError in strict ESM and would silently no-op via the catch. - const nodeRequire = createRequire(import.meta.url); - const { Config } = nodeRequire("apcore-js"); - if (typeof Config?.registerNamespace === "function") { - Config.registerNamespace({ - name: "apcore-cli", - envPrefix: "APCORE_CLI", - defaults: NAMESPACE_DEFAULTS, - }); - } + Config.registerNamespace({ + name: "apcore-cli", + envPrefix: "APCORE_CLI", + defaults: NAMESPACE_DEFAULTS, + }); } catch { - // apcore-js not installed or < 0.15.0 — graceful no-op + // The namespace can already be registered when a host builds another CLI. } } diff --git a/cli/typescript/src/security/sandbox.ts b/cli/typescript/src/security/sandbox.ts index af20b21f..3e6951fd 100644 --- a/cli/typescript/src/security/sandbox.ts +++ b/cli/typescript/src/security/sandbox.ts @@ -250,7 +250,7 @@ export async function runSandboxRunner(moduleId: string): Promise { const extensionsRoot = process.env.APCORE_EXTENSIONS_ROOT ?? "./extensions"; // Dynamic import avoids circular deps and keeps the sandbox runner // isolated from the host CLI initialization code. - const apcore = await import("apcore-js").catch(() => { + const apcore = await import("apcore-js/full").catch(() => { process.stderr.write( "sandbox runner: apcore-js is not available in the sandboxed environment.\n", ); diff --git a/cli/typescript/src/system-cmd.ts b/cli/typescript/src/system-cmd.ts index 55be64d7..5a384af1 100644 --- a/cli/typescript/src/system-cmd.ts +++ b/cli/typescript/src/system-cmd.ts @@ -7,7 +7,7 @@ */ import { Command } from "commander"; -import { Config } from "apcore-js"; +import { Config } from "apcore-js/config"; import { checkApproval } from "./approval.js"; import type { Executor, ModuleDescriptor } from "./cli.js"; import { exitCodeForError } from "./errors.js"; diff --git a/cli/typescript/tests/acl-governance.test.ts b/cli/typescript/tests/acl-governance.test.ts index 12d8a0ea..c0fb3f26 100644 --- a/cli/typescript/tests/acl-governance.test.ts +++ b/cli/typescript/tests/acl-governance.test.ts @@ -18,7 +18,8 @@ import * as fs from "node:fs"; import * as os from "node:os"; import * as path from "node:path"; import { Command } from "commander"; -import { ACL, APCore } from "apcore-js"; +import { APCore } from "apcore-js"; +import { ACL } from "apcore-js/full"; import { registerAclCommand } from "../src/acl-cmd.js"; import { diff --git a/mcp/conformance/README.md b/mcp/conformance/README.md index c9f38aed..716d9620 100644 --- a/mcp/conformance/README.md +++ b/mcp/conformance/README.md @@ -39,6 +39,11 @@ from MCP discovery expectations; standalone converter and OpenAI fixtures are un ### Driven by all three bridges +`tool_projection.json` verifies the same module across the public MCP tool factory, +OpenAI Chat and Responses exporters, and Anthropic exporter in all three SDKs. +It covers distinct tool envelopes, strict options, recursive references, +schema extension handling, and approval metadata. + `acl_config.json` at `contract_version` 1.2 and `openapi_backend.json` are driven by `apcore-mcp-python`, `apcore-mcp-typescript` and `apcore-mcp-rust` as of each bridge's 0.20.0. Their expectations were computed by running the real upstreams — apcore 0.29.0's `ACLRule` errors diff --git a/mcp/conformance/fixtures/tool_projection.json b/mcp/conformance/fixtures/tool_projection.json new file mode 100644 index 00000000..17d5052c --- /dev/null +++ b/mcp/conformance/fixtures/tool_projection.json @@ -0,0 +1,74 @@ +{ + "description": "Provider tool envelopes share canonical names and strict schema conversion, with an explicit Responses strict opt-out.", + "module": { + "module_id": "demo.send", + "description": "Send a message", + "input_schema": { + "type": "object", + "properties": { + "to": {"type": "string", "x-llm-description": "Recipient", "x-sensitive": true}, + "x-trace": {"type": "string", "default": "local"} + }, + "required": ["to"] + }, + "output_schema": {"type": "object", "properties": {"sent": {"type": "boolean"}}}, + "examples": [{"title": "Sample", "inputs": {"to": "sample"}, "output": {}}] + }, + "recursive_input_schema": { + "type": "object", + "properties": {"tree": {"$ref": "#/$defs/node"}}, + "$defs": { + "node": { + "type": "object", + "properties": { + "children": {"type": "array", "items": {"$ref": "#/$defs/node"}} + }, + "required": ["children"] + } + } + }, + "expected": { + "mcp_meta": {"requiresApproval": true, "streaming": true}, + "openai_chat": { + "type": "function", + "function": { + "name": "demo-send", + "description": "Send a message", + "parameters": { + "type": "object", + "properties": {"to": {"type": "string", "description": "Recipient"}, "x-trace": {"type": ["string", "null"]}}, + "required": ["to", "x-trace"], + "additionalProperties": false + }, + "strict": true + } + }, + "openai_responses_non_strict": { + "type": "function", + "name": "demo-send", + "description": "Send a message", + "parameters": { + "type": "object", + "properties": { + "to": {"type": "string", "x-llm-description": "Recipient", "x-sensitive": true}, + "x-trace": {"type": "string", "default": "local"} + }, + "required": ["to"] + }, + "strict": false + }, + "anthropic": { + "name": "demo-send", + "description": "Send a message", + "input_schema": { + "type": "object", + "properties": { + "to": {"type": "string", "description": "Recipient"}, + "x-trace": {"type": "string", "default": "local"} + }, + "required": ["to"] + }, + "input_examples": [{"to": "sample"}] + } + } +} diff --git a/mcp/docs/features/openai-converter.md b/mcp/docs/features/openai-converter.md index dfd106d1..c05dd7ba 100644 --- a/mcp/docs/features/openai-converter.md +++ b/mcp/docs/features/openai-converter.md @@ -68,10 +68,25 @@ When `strict=True`, the converter performs recursive transformation: - Convert any property that wasn't originally required into a union type `[type, "null"]`. - Strip all `default` values and non-standard `x-*` keys. -### Per-SDK Defaults (v0.14.0) -- Python: `OpenAIConverter()` — strict default `false`; pass `strict=true` per call. -- TypeScript: `convertRegistry(registry, { strict: true })` — strict default `true` (changed in 0.14.0 per OC-1). -- Rust: explicit `strict: bool` argument required on `convert_registry`/`convert_descriptor`; no implicit default. +### Tool formats and defaults + +The default OpenAI conversion uses strict schemas. Rust positional calls still +take an explicit `strict` argument. Rust `ConvertOptions::default()` selects +strict mode. Provider converters preserve local references and definitions. + +| Target | Python | TypeScript | Rust | +| --- | --- | --- | --- | +| OpenAI Chat Completions | `OpenAIConverter.convert_descriptor` | `OpenAIConverter.convertDescriptor` | `OpenAIConverter::convert_descriptor_with_options` | +| OpenAI Responses | `OpenAIConverter.convert_responses_descriptor` | `OpenAIConverter.convertResponsesDescriptor` | `OpenAIConverter::convert_responses_descriptor` | +| Anthropic Messages | `AnthropicConverter.convert_descriptor` | `AnthropicConverter.convertDescriptor` | `AnthropicConverter::convert_descriptor` | + +Chat Completions puts the definition in `function`. Responses puts the +definition fields at the tool's top level. The Responses exporter emits explicit +`strict: false` for opt-out. Both OpenAI formats can project all applicable +modules from a registry. [OpenAI function calling](https://developers.openai.com/api/docs/guides/function-calling). + +Anthropic returns `name`, `description`, and `input_schema`. Module +input examples populate `input_examples`. [Anthropic tool definitions](https://platform.claude.com/docs/en/agents-and-tools/tool-use/define-tools). ### Module ID Normalization Since OpenAI function names can only contain `[a-zA-Z0-9_-]`, dots are replaced with hyphens. The converter must ensure this mapping is bijective and reversible to allow the calling application to map the tool call back to the original `module_id`. @@ -87,7 +102,7 @@ The converter must return only standard Python types (dict, list, str, etc.) and ## Error Handling -- **Incompatible Schema**: If a schema cannot be converted to OpenAI's strict format (e.g., it uses unsupported keywords), the converter logs a warning and provides the best possible non-strict alternative. +- **Incompatible Schema**: The provider validates its supported keyword set. Prefer a compatible schema for strict mode, or explicitly select non-strict conversion. - **ID Conflict**: If normalization results in name collisions (e.g., `a.b` and `a-b` both become `a-b`), the converter raises a `ValueError`. ## Notes @@ -221,7 +236,9 @@ The converter must return only standard Python types (dict, list, str, etc.) and - idempotent: true ### Default -`ConvertOptions::default()` returns `{strict: false, embed_annotations: false, rich_description: false, tags: None, prefix: None}`. Callers using the default Boolean strict semantics SHOULD use the non-`_with_options` `convert_registry(registry, strict)` form for clarity. +`ConvertOptions::default()` sets `strict = true`, `embed_annotations = false`, +and `rich_description = false`. Registry methods accept tag and prefix filters +separately. --- diff --git a/mcp/python/pyproject.toml b/mcp/python/pyproject.toml index 443d0d3b..b2ee177a 100644 --- a/mcp/python/pyproject.toml +++ b/mcp/python/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "hatchling.build" [project] name = "apcore-mcp" -version = "0.23.5a1" +version = "0.23.5a2" description = "Automatic MCP Server & OpenAI Tools Bridge for apcore" readme = "README.md" license = "Apache-2.0" @@ -25,7 +25,7 @@ classifiers = [ "Topic :: Scientific/Engineering :: Artificial Intelligence", ] dependencies = [ - "apcore>=0.33.0,<=1.0.0a1", + "apcore[config,discovery]==1.0.0a2", "mcp>=1.26,<2.0", "jsonschema>=4.20,<5", "referencing>=0.30,<1", @@ -51,7 +51,7 @@ markdown = [ # entry point raises with an actionable install message instead of returning # None. openapi = [ - "apcore-toolkit[http-proxy]==0.15.1a1", + "apcore-toolkit[http-proxy]==0.15.1a2", ] dev = [ @@ -61,7 +61,7 @@ dev = [ "mypy>=1.0", "ruff>=0.1", "apdev[dev]>=0.2.3", - "apcore-toolkit[http-proxy]==0.15.1a1", + "apcore-toolkit[http-proxy]==0.15.1a2", ] [project.scripts] diff --git a/mcp/python/src/apcore_mcp/__init__.py b/mcp/python/src/apcore_mcp/__init__.py index b28e5a7d..6f20226f 100644 --- a/mcp/python/src/apcore_mcp/__init__.py +++ b/mcp/python/src/apcore_mcp/__init__.py @@ -40,6 +40,7 @@ ) from apcore_mcp.config import MCP_DEFAULTS, MCP_ENV_PREFIX, MCP_NAMESPACE, register_mcp_namespace from apcore_mcp.constants import APCORE_EVENTS, ERROR_CODES, MODULE_ID_PATTERN, REGISTRY_EVENTS +from apcore_mcp.converters.anthropic import AnthropicConverter from apcore_mcp.converters.openai import OpenAIConverter from apcore_mcp.helpers import MCP_ELICIT_KEY, MCP_PROGRESS_KEY, ElicitResult, elicit, report_progress from apcore_mcp.server.approval_bridge import APPROVAL_META_TOOL_NAMES, ApprovalBridge @@ -109,6 +110,7 @@ "ModuleIDNormalizer", "internal_error_response", # Converters + "AnthropicConverter", "OpenAIConverter", # Config Bus "MCP_NAMESPACE", @@ -404,7 +406,7 @@ def to_openai_tools( registry_or_executor: object | None = None, *, embed_annotations: bool = False, - strict: bool = False, + strict: bool = True, tags: list[str] | None = None, prefix: str | None = None, ) -> list[dict]: diff --git a/mcp/python/src/apcore_mcp/__main__.py b/mcp/python/src/apcore_mcp/__main__.py index fd8c39f5..3afd5955 100644 --- a/mcp/python/src/apcore_mcp/__main__.py +++ b/mcp/python/src/apcore_mcp/__main__.py @@ -234,7 +234,7 @@ def _run(args: argparse.Namespace, parser: argparse.ArgumentParser) -> None: if extensions_dir is None and not args.from_openapi: has_config_bus_openapi = False try: - from apcore import Config + from apcore.config import Config _config = Config.load() has_config_bus_openapi = bool(_config and _config.get("mcp.openapi")) @@ -287,7 +287,9 @@ def _run(args: argparse.Namespace, parser: argparse.ArgumentParser) -> None: # directory first, then OpenAPI operations — so a collision report names # the OpenAPI side, which is the one the operator can rename with a prefix. if extensions_dir is not None: - registry = Registry(extensions_dir=str(extensions_dir)) + from apcore.discovery import Registry as DiscoveryRegistry + + registry = DiscoveryRegistry(extensions_dir=str(extensions_dir)) num_modules = registry.discover() if num_modules == 0: logger.warning("No modules discovered in '%s'.", extensions_dir) diff --git a/mcp/python/src/apcore_mcp/acl_builder.py b/mcp/python/src/apcore_mcp/acl_builder.py index 876bfbdf..e0f9f96c 100644 --- a/mcp/python/src/apcore_mcp/acl_builder.py +++ b/mcp/python/src/apcore_mcp/acl_builder.py @@ -111,7 +111,7 @@ def build_acl_from_config(acl_config: Any | None) -> Any | None: ) try: - from apcore import ACL, ACLRule + from apcore.acl import ACL, ACLRule except ImportError as exc: raise RuntimeError("Config Bus `mcp.acl` requires apcore>=0.18 with ACL support") from exc diff --git a/mcp/python/src/apcore_mcp/adapters/schema.py b/mcp/python/src/apcore_mcp/adapters/schema.py index fb91b91e..1fca0933 100644 --- a/mcp/python/src/apcore_mcp/adapters/schema.py +++ b/mcp/python/src/apcore_mcp/adapters/schema.py @@ -12,7 +12,7 @@ # should be walked when injecting additionalProperties: false. Keys like # ``enum``, ``const``, ``examples``, ``default``, ``required`` hold literal # data and must NOT be recursed into. -_SCHEMA_CHILD_DICT_KEYS = ("properties", "patternProperties", "$defs", "definitions") +_SCHEMA_CHILD_DICT_KEYS = ("properties", "patternProperties", "$defs", "definitions", "dependentSchemas") _SCHEMA_CHILD_LIST_KEYS = ("oneOf", "anyOf", "allOf", "prefixItems") _SCHEMA_CHILD_SCHEMA_KEYS = ("items", "not", "if", "then", "else", "contains", "propertyNames") @@ -49,6 +49,14 @@ def apply_llm_descriptions(schema: dict[str, Any]) -> None: node["description"] = description +def strip_schema_extensions(schema: dict[str, Any]) -> None: + """Remove APCore extensions while preserving schemas' literal values.""" + for node in _schema_nodes(schema): + for key in tuple(node): + if key.startswith("x-"): + del node[key] + + class SchemaConverter: """Converts apcore ModuleDescriptor schemas to MCP-compatible schemas. @@ -65,19 +73,22 @@ class SchemaConverter: def __init__(self, *, strict: bool = True) -> None: self._strict = strict - def convert_input_schema(self, descriptor: Any, *, strict: bool | None = None) -> dict[str, Any]: + def convert_input_schema( + self, descriptor: Any, *, strict: bool | None = None, inline_refs: bool = True + ) -> dict[str, Any]: """Convert apcore ModuleDescriptor.input_schema to MCP inputSchema. Args: descriptor: ModuleDescriptor with input_schema attribute strict: Per-call override of the construction-time strict mode. ``None`` keeps the converter's own setting. + inline_refs: Resolve references when the target requires inlined schemas. Returns: MCP-compatible schema dict with $refs inlined and $defs removed """ schema = descriptor.input_schema - return self._convert_schema(schema, strict=strict) + return self._convert_schema(schema, strict=strict, inline_refs=inline_refs) def convert_output_schema(self, descriptor: Any, *, strict: bool | None = None) -> dict[str, Any]: """Convert apcore ModuleDescriptor.output_schema. @@ -93,13 +104,16 @@ def convert_output_schema(self, descriptor: Any, *, strict: bool | None = None) schema = descriptor.output_schema return self._convert_schema(schema, strict=strict) - def _convert_schema(self, schema: dict[str, Any], *, strict: bool | None = None) -> dict[str, Any]: + def _convert_schema( + self, schema: dict[str, Any], *, strict: bool | None = None, inline_refs: bool = True + ) -> dict[str, Any]: """Convert a schema, applying all transformations. Args: schema: JSON Schema dict to convert strict: Per-call override of the construction-time strict mode. ``None`` keeps the converter's own setting. + inline_refs: Resolve references against definitions in the schema. Returns: Converted schema with $refs inlined, $defs removed, and type ensured @@ -121,7 +135,7 @@ def _convert_schema(self, schema: dict[str, Any], *, strict: bool | None = None) return result # Inline $refs if present - if "$defs" in schema: + if inline_refs and "$defs" in schema: defs = schema["$defs"] schema = self._inline_refs(schema, defs) # Remove $defs from the final schema diff --git a/mcp/python/src/apcore_mcp/apcore_mcp.py b/mcp/python/src/apcore_mcp/apcore_mcp.py index 89b2c390..4cd2eb12 100644 --- a/mcp/python/src/apcore_mcp/apcore_mcp.py +++ b/mcp/python/src/apcore_mcp/apcore_mcp.py @@ -61,7 +61,8 @@ def _load_config_bus_overrides( config_acl: object | None = None scalars: dict[str, object] = {} try: - from apcore import Config, build_strategy_from_config + from apcore.config import Config + from apcore.pipeline_config import build_strategy_from_config except ImportError as exc: logger.debug("Config Bus not available, skipping: %s", exc) return { @@ -495,7 +496,7 @@ def __init__( # explicit from_openapi()/openapi_backend() call required. openapi_config: Any | None = None try: - from apcore import Config + from apcore.config import Config _config = Config.load() if _config: @@ -515,7 +516,7 @@ def __init__( backend: Any = build_openapi_backend_from_config(openapi_config) elif isinstance(extensions_dir_or_backend, str | Path): - from apcore import Registry + from apcore.discovery import Registry backend = Registry(extensions_dir=str(extensions_dir_or_backend)) backend.discover() diff --git a/mcp/python/src/apcore_mcp/converters/__init__.py b/mcp/python/src/apcore_mcp/converters/__init__.py index 25d586dd..85005e7d 100644 --- a/mcp/python/src/apcore_mcp/converters/__init__.py +++ b/mcp/python/src/apcore_mcp/converters/__init__.py @@ -1 +1 @@ -"""Converters: OpenAI tools format conversion.""" +"""Project APCore modules to model provider tool formats.""" diff --git a/mcp/python/src/apcore_mcp/converters/anthropic.py b/mcp/python/src/apcore_mcp/converters/anthropic.py new file mode 100644 index 00000000..077aa757 --- /dev/null +++ b/mcp/python/src/apcore_mcp/converters/anthropic.py @@ -0,0 +1,31 @@ +"""Project APCore module descriptors into Anthropic Messages tools.""" + +from __future__ import annotations + +from copy import deepcopy +from typing import Any + +from apcore_mcp.adapters.id_normalizer import ModuleIDNormalizer +from apcore_mcp.adapters.schema import apply_llm_descriptions, strip_schema_extensions + + +class AnthropicConverter: + """Convert one module descriptor to an Anthropic Messages tool.""" + + def __init__(self) -> None: + self._names = ModuleIDNormalizer() + + def convert_descriptor(self, descriptor: Any) -> dict[str, Any]: + """Preserve input constraints and expose descriptor input examples.""" + schema = deepcopy(descriptor.input_schema) + apply_llm_descriptions(schema) + strip_schema_extensions(schema) + tool = { + "name": self._names.normalize(descriptor.module_id), + "description": descriptor.description, + "input_schema": schema, + } + examples = getattr(descriptor, "examples", None) + if examples: + tool["input_examples"] = [deepcopy(example.inputs) for example in examples] + return tool diff --git a/mcp/python/src/apcore_mcp/converters/openai.py b/mcp/python/src/apcore_mcp/converters/openai.py index 1a6db5f5..1ec9da1d 100644 --- a/mcp/python/src/apcore_mcp/converters/openai.py +++ b/mcp/python/src/apcore_mcp/converters/openai.py @@ -32,7 +32,7 @@ def convert_registry( self, registry: Any, embed_annotations: bool = False, - strict: bool = False, + strict: bool = True, tags: list[str] | None = None, prefix: str | None = None, rich_description: bool = False, @@ -106,7 +106,7 @@ def convert_descriptor( descriptor: ModuleDescriptor with module_id, description, input_schema, and optional annotations. embed_annotations: If True, append annotation hints to description. - strict: If True (default since 0.16.0, parity with TS), enable OpenAI + strict: If True (the default), enable OpenAI strict mode: inject ``additionalProperties: false``, hoist all properties into ``required`` (with optionals widened to nullable), and emit ``strict: true`` on the function. [D11-5] @@ -126,7 +126,7 @@ def convert_descriptor( } """ name = self._id_normalizer.normalize(descriptor.module_id) - parameters = self._schema_converter.convert_input_schema(descriptor) + parameters = self._schema_converter.convert_input_schema(descriptor, strict=False, inline_refs=False) description = self._render_description( descriptor, @@ -153,6 +153,32 @@ def convert_descriptor( "function": function, } + def convert_responses_descriptor( + self, + descriptor: Any, + *, + embed_annotations: bool = False, + strict: bool = True, + rich_description: bool = False, + ) -> dict[str, Any]: + """Convert a module to a Responses API function tool.""" + chat = self.convert_descriptor(descriptor, embed_annotations, strict, rich_description) + return {"type": "function", **chat["function"], "strict": strict} + + def convert_responses_registry( + self, + registry: Any, + *, + embed_annotations: bool = False, + strict: bool = True, + tags: list[str] | None = None, + prefix: str | None = None, + rich_description: bool = False, + ) -> list[dict[str, Any]]: + """Convert a registry to Responses API function tools.""" + tools = self.convert_registry(registry, embed_annotations, strict, tags, prefix, rich_description) + return [{"type": "function", **tool["function"], "strict": strict} for tool in tools] + def _render_description( self, descriptor: Any, diff --git a/mcp/python/src/apcore_mcp/middleware_builder.py b/mcp/python/src/apcore_mcp/middleware_builder.py index d8022a24..6e800015 100644 --- a/mcp/python/src/apcore_mcp/middleware_builder.py +++ b/mcp/python/src/apcore_mcp/middleware_builder.py @@ -41,11 +41,8 @@ def build_middleware_from_config(entries: list[dict[str, Any]]) -> list[Any]: return [] try: - from apcore import ( - ErrorHistoryMiddleware, - RetryConfig, - RetryMiddleware, - ) + from apcore.middleware.error_history_middleware import ErrorHistoryMiddleware + from apcore.middleware.retry import RetryConfig, RetryMiddleware except ImportError as exc: raise RuntimeError("Config Bus `mcp.middleware` requires apcore>=0.18 with middleware support") from exc diff --git a/mcp/python/src/apcore_mcp/openapi_backend.py b/mcp/python/src/apcore_mcp/openapi_backend.py index cb471dd3..64eef932 100644 --- a/mcp/python/src/apcore_mcp/openapi_backend.py +++ b/mcp/python/src/apcore_mcp/openapi_backend.py @@ -205,7 +205,7 @@ def openapi_backend( ``apcore-mcp/docs/features/openapi-backend.md``. """ toolkit = _require_toolkit() - from apcore import Registry + from apcore.registry import Registry if has_other_backend_source and not prefix: raise ValueError( diff --git a/mcp/python/tests/converters/test_openai.py b/mcp/python/tests/converters/test_openai.py index 290c04a5..700d4f96 100644 --- a/mcp/python/tests/converters/test_openai.py +++ b/mcp/python/tests/converters/test_openai.py @@ -4,8 +4,11 @@ import pytest +from apcore_mcp import AnthropicConverter from apcore_mcp.converters.openai import OpenAIConverter -from tests.conftest import ModuleAnnotations, ModuleDescriptor +from apcore_mcp.server.factory import MCPServerFactory +from tests.conformance_fixtures import load_fixture +from tests.conftest import ModuleAnnotations, ModuleDescriptor, ModuleExample # --------------------------------------------------------------------------- # Lightweight stub for apcore Registry used in converter tests. @@ -29,6 +32,36 @@ def get_definition(self, module_id): return self._descriptors.get(module_id) +def test_provider_tool_projection(): + fixture = load_fixture("tool_projection.json") + module = fixture["module"] + descriptor = ModuleDescriptor(**{**module, "examples": [ModuleExample(**e) for e in module["examples"]]}) + registry = StubRegistry([descriptor]) + openai = OpenAIConverter() + expected = fixture["expected"] + assert openai.convert_registry(registry) == [expected["openai_chat"]] + assert openai.convert_responses_descriptor(descriptor, strict=False) == expected["openai_responses_non_strict"] + assert openai.convert_responses_registry(registry) == [{"type": "function", **expected["openai_chat"]["function"]}] + assert AnthropicConverter().convert_descriptor(descriptor) == expected["anthropic"] + + factory = MCPServerFactory() + descriptor.annotations = ModuleAnnotations(requires_approval=True, streaming=True) + tool = factory.build_tool(descriptor) + assert tool.name == descriptor.module_id + assert tool.inputSchema == descriptor.input_schema + assert tool.outputSchema == descriptor.output_schema + assert tool.meta == expected["mcp_meta"] + assert "requiresApproval" not in tool.annotations.model_dump() + assert "streaming" not in tool.annotations.model_dump() + descriptor.annotations = ModuleAnnotations() + assert factory.build_tool(descriptor).meta is None + + descriptor.input_schema = fixture["recursive_input_schema"] + assert AnthropicConverter().convert_descriptor(descriptor)["input_schema"] == descriptor.input_schema + params = openai.convert_descriptor(descriptor)["function"]["parameters"] + assert params["$defs"]["node"]["properties"]["children"]["items"]["$ref"] == "#/$defs/node" + + class TestConvertDescriptor: """Tests for OpenAIConverter.convert_descriptor.""" diff --git a/mcp/python/tests/test_acl.py b/mcp/python/tests/test_acl.py index 75add580..555f637f 100644 --- a/mcp/python/tests/test_acl.py +++ b/mcp/python/tests/test_acl.py @@ -179,7 +179,7 @@ def test_apcore_mcp_reads_acl_from_config_bus(): }, }.get(key) - with patch("apcore.Config.load", return_value=fake_config): + with patch("apcore.config.Config.load", return_value=fake_config): mcp = APCoreMCP(registry) # The executor should have an ACL installed (not None) — the apcore 0.18+ @@ -215,7 +215,7 @@ def test_apcore_mcp_caller_acl_overrides_config_bus(): default_effect="deny", ) - with patch("apcore.Config.load", return_value=fake_config): + with patch("apcore.config.Config.load", return_value=fake_config): mcp = APCoreMCP(registry, acl=explicit_acl) # Verify the executor holds the *explicit* ACL, not the Config Bus one. diff --git a/mcp/python/tests/test_acl_approval_gating_e2e.py b/mcp/python/tests/test_acl_approval_gating_e2e.py index 5d85601c..de5550c7 100644 --- a/mcp/python/tests/test_acl_approval_gating_e2e.py +++ b/mcp/python/tests/test_acl_approval_gating_e2e.py @@ -52,7 +52,7 @@ class _DeleteModule: description = "Delete a path" # Deliberately false: any approval requirement observed in these tests can # only have come from the ACL rule, which is the whole point. - annotations = {"requires_approval": False, "destructive": True} + annotations = {"requires_approval": False} def execute(self, inputs: dict[str, Any], context: Any) -> dict[str, Any]: return {"deleted": inputs["path"]} diff --git a/mcp/python/tests/test_apcore_mcp.py b/mcp/python/tests/test_apcore_mcp.py index 7d4f3a4a..edc39b95 100644 --- a/mcp/python/tests/test_apcore_mcp.py +++ b/mcp/python/tests/test_apcore_mcp.py @@ -113,7 +113,7 @@ def test_from_executor(self) -> None: def test_from_extensions_dir(self) -> None: mock_registry = MagicMock(spec=["list", "get_definition", "discover"]) mock_registry.list.return_value = [] - with patch("apcore.Registry", return_value=mock_registry) as mock_cls: + with patch("apcore.discovery.Registry", return_value=mock_registry) as mock_cls: mcp = APCoreMCP("/tmp/extensions") mock_cls.assert_called_once_with(extensions_dir="/tmp/extensions") mock_registry.discover.assert_called_once() @@ -123,7 +123,7 @@ def test_from_path_object(self) -> None: from pathlib import Path mock_registry = StubRegistry() - with patch("apcore.Registry", return_value=mock_registry) as mock_cls: + with patch("apcore.discovery.Registry", return_value=mock_registry) as mock_cls: APCoreMCP(Path("/tmp/extensions")) mock_cls.assert_called_once_with(extensions_dir="/tmp/extensions") diff --git a/mcp/python/tests/test_api.py b/mcp/python/tests/test_api.py index 36eb9c8a..c4eef386 100644 --- a/mcp/python/tests/test_api.py +++ b/mcp/python/tests/test_api.py @@ -126,24 +126,14 @@ def test_returns_executor_directly(self, executor): def test_creates_executor_from_registry(self, registry): """When given a registry, imports and creates an Executor.""" - import sys - mock_executor_cls = MagicMock() mock_executor_instance = MagicMock() mock_executor_cls.return_value = mock_executor_instance - fake_apcore_executor = MagicMock() - fake_apcore_executor.Executor = mock_executor_cls - sys.modules["apcore"] = MagicMock() - sys.modules["apcore.executor"] = fake_apcore_executor - - try: + with patch("apcore.executor.Executor", mock_executor_cls): result = resolve_executor(registry) mock_executor_cls.assert_called_once_with(registry, approval_handler=None) assert result is mock_executor_instance - finally: - del sys.modules["apcore.executor"] - del sys.modules["apcore"] # =========================================================================== diff --git a/mcp/python/tests/test_cli.py b/mcp/python/tests/test_cli.py index 0eda0506..da65a749 100644 --- a/mcp/python/tests/test_cli.py +++ b/mcp/python/tests/test_cli.py @@ -35,7 +35,7 @@ def _make_patches(stub_registry_cls=None, discover_return=5): mock_registry_cls = stub_registry_cls return { - "registry_patch": patch("apcore_mcp.__main__.Registry", mock_registry_cls), + "registry_patch": patch("apcore.discovery.Registry", mock_registry_cls), "serve_patch": patch("apcore_mcp.__main__.serve"), "mock_registry_cls": mock_registry_cls, } @@ -301,7 +301,7 @@ def test_main_creates_registry_discovers_and_serves(self, tmp_path): mock_registry_cls.return_value = mock_instance with ( - patch("apcore_mcp.__main__.Registry", mock_registry_cls) as mock_reg, + patch("apcore.discovery.Registry", mock_registry_cls) as mock_reg, patch("apcore_mcp.__main__.serve") as mock_serve, ): _run_main("--extensions-dir", str(tmp_path)) @@ -324,7 +324,7 @@ def test_zero_modules_still_starts_server(self, tmp_path): mock_registry_cls.return_value = mock_instance with ( - patch("apcore_mcp.__main__.Registry", mock_registry_cls), + patch("apcore.discovery.Registry", mock_registry_cls), patch("apcore_mcp.__main__.serve") as mock_serve, ): _run_main("--extensions-dir", str(tmp_path)) @@ -340,7 +340,7 @@ def test_serve_exception_exits_2(self, tmp_path, capsys): mock_registry_cls.return_value = mock_instance with ( - patch("apcore_mcp.__main__.Registry", mock_registry_cls), + patch("apcore.discovery.Registry", mock_registry_cls), patch("apcore_mcp.__main__.serve", side_effect=RuntimeError("bind failed")), ): with pytest.raises(SystemExit) as exc_info: @@ -611,7 +611,7 @@ def test_config_bus_openapi_present_does_not_exit(self): with ( patches["registry_patch"], patches["serve_patch"] as mock_serve, - patch("apcore.Config") as mock_cfg_cls, + patch("apcore.config.Config") as mock_cfg_cls, ): mock_cfg_cls.load.return_value = fake_cfg _run_main() # no --extensions-dir, no --from-openapi @@ -624,7 +624,7 @@ def test_config_bus_openapi_present_does_not_exit(self): def test_neither_flag_nor_config_bus_still_exits_2(self, capsys): fake_cfg = _FakeMcpOpenapiConfig(None) - with patch("apcore.Config") as mock_cfg_cls: + with patch("apcore.config.Config") as mock_cfg_cls: mock_cfg_cls.load.return_value = fake_cfg with pytest.raises(SystemExit) as exc_info: _run_main() diff --git a/mcp/python/tests/test_config_bus_overrides.py b/mcp/python/tests/test_config_bus_overrides.py index e144999e..43fb3a39 100644 --- a/mcp/python/tests/test_config_bus_overrides.py +++ b/mcp/python/tests/test_config_bus_overrides.py @@ -52,7 +52,7 @@ def test_all_scalars_propagate(self, fake_registry: _FakeRegistry) -> None: } fake_cfg = _FakeConfig(store) - with patch("apcore.Config") as mock_cfg_cls: + with patch("apcore.config.Config") as mock_cfg_cls: mock_cfg_cls.load.return_value = fake_cfg result = apcore_mcp._load_config_bus_overrides( registry=fake_registry, @@ -74,7 +74,7 @@ def test_all_scalars_propagate(self, fake_registry: _FakeRegistry) -> None: def test_port_string_coerced_to_int(self, fake_registry: _FakeRegistry) -> None: """``mcp.port`` may arrive as a string from env vars — coerce to int.""" fake_cfg = _FakeConfig({"mcp.port": "8080"}) - with patch("apcore.Config") as mock_cfg_cls: + with patch("apcore.config.Config") as mock_cfg_cls: mock_cfg_cls.load.return_value = fake_cfg result = apcore_mcp._load_config_bus_overrides( registry=fake_registry, @@ -85,7 +85,7 @@ def test_port_string_coerced_to_int(self, fake_registry: _FakeRegistry) -> None: def test_port_garbage_string_is_ignored(self, fake_registry: _FakeRegistry) -> None: fake_cfg = _FakeConfig({"mcp.port": "not-a-number"}) - with patch("apcore.Config") as mock_cfg_cls: + with patch("apcore.config.Config") as mock_cfg_cls: mock_cfg_cls.load.return_value = fake_cfg result = apcore_mcp._load_config_bus_overrides( registry=fake_registry, @@ -96,7 +96,7 @@ def test_port_garbage_string_is_ignored(self, fake_registry: _FakeRegistry) -> N def test_empty_config_returns_empty_scalars(self, fake_registry: _FakeRegistry) -> None: fake_cfg = _FakeConfig({}) - with patch("apcore.Config") as mock_cfg_cls: + with patch("apcore.config.Config") as mock_cfg_cls: mock_cfg_cls.load.return_value = fake_cfg result = apcore_mcp._load_config_bus_overrides( registry=fake_registry, @@ -136,7 +136,10 @@ class TestLoadConfigBusOverridesPipelineFlag: def test_pipeline_skipped_when_flag_false(self, fake_registry: _FakeRegistry) -> None: fake_cfg = _FakeConfig({"mcp.pipeline": {"name": "standard"}}) - with patch("apcore.Config") as mock_cfg_cls, patch("apcore.build_strategy_from_config") as mock_build: + with ( + patch("apcore.config.Config") as mock_cfg_cls, + patch("apcore.pipeline_config.build_strategy_from_config") as mock_build, + ): mock_cfg_cls.load.return_value = fake_cfg mock_build.return_value = "BUILT" result = apcore_mcp._load_config_bus_overrides( @@ -149,7 +152,10 @@ def test_pipeline_skipped_when_flag_false(self, fake_registry: _FakeRegistry) -> def test_pipeline_consumed_when_flag_true(self, fake_registry: _FakeRegistry) -> None: fake_cfg = _FakeConfig({"mcp.pipeline": {"name": "standard"}}) - with patch("apcore.Config") as mock_cfg_cls, patch("apcore.build_strategy_from_config") as mock_build: + with ( + patch("apcore.config.Config") as mock_cfg_cls, + patch("apcore.pipeline_config.build_strategy_from_config") as mock_build, + ): mock_cfg_cls.load.return_value = fake_cfg mock_build.return_value = "BUILT" result = apcore_mcp._load_config_bus_overrides( diff --git a/mcp/python/tests/test_d4_d9_d10_d11_fixes.py b/mcp/python/tests/test_d4_d9_d10_d11_fixes.py index b3925975..de03b853 100644 --- a/mcp/python/tests/test_d4_d9_d10_d11_fixes.py +++ b/mcp/python/tests/test_d4_d9_d10_d11_fixes.py @@ -235,7 +235,7 @@ async def capturing_run_http(server, init_opts, *, host, port, **kwargs): mock_tm.run_streamable_http = capturing_run_http # Patch Config.load() to return our mock config - with patch("apcore.Config") as mock_config_cls: + with patch("apcore.config.Config") as mock_config_cls: mock_config_cls.load.return_value = mock_config # Monkey-patch resolve_registry/resolve_executor at their canonical diff --git a/mcp/python/tests/test_management_surfaces.py b/mcp/python/tests/test_management_surfaces.py index 56760f88..10de6b1b 100644 --- a/mcp/python/tests/test_management_surfaces.py +++ b/mcp/python/tests/test_management_surfaces.py @@ -188,7 +188,9 @@ def test_unprotected_system_control_warns_on_build(self, caplog: pytest.LogCaptu from apcore_mcp.apcore_mcp import APCoreMCP registry = Registry() - executor = Executor(registry=registry) + from apcore.policy import ExecutionPolicy + + executor = Executor(registry=registry, policy=ExecutionPolicy(strict=False)) register_sys_modules(registry=registry, executor=executor, config=_sys_modules_config()) mcp = APCoreMCP(executor, async_tasks=False) diff --git a/mcp/python/tests/test_middleware.py b/mcp/python/tests/test_middleware.py index 75f2efee..90b9a516 100644 --- a/mcp/python/tests/test_middleware.py +++ b/mcp/python/tests/test_middleware.py @@ -168,7 +168,7 @@ def test_apcore_mcp_reads_config_bus_middleware(): fake_config = MagicMock() fake_config.get.side_effect = lambda key, *a, **kw: config_data.get(key) - with patch("apcore.Config.load", return_value=fake_config): + with patch("apcore.config.Config.load", return_value=fake_config): mcp = APCoreMCP(registry) mws = list(mcp._executor._middleware_manager._middlewares) @@ -194,7 +194,7 @@ def test_apcore_mcp_merges_config_and_constructor_middleware(): fake_config.get.side_effect = lambda key, *a, **kw: config_data.get(key) user_mw = ObsLoggingMiddleware() - with patch("apcore.Config.load", return_value=fake_config): + with patch("apcore.config.Config.load", return_value=fake_config): mcp = APCoreMCP(registry, middleware=[user_mw]) mws = list(mcp._executor._middleware_manager._middlewares) @@ -211,7 +211,7 @@ def test_apcore_mcp_no_config_bus_still_works(): registry = Registry() user_mw = RetryMiddleware() - with patch("apcore.Config.load", return_value=None): + with patch("apcore.config.Config.load", return_value=None): mcp = APCoreMCP(registry, middleware=[user_mw]) assert user_mw in list(mcp._executor._middleware_manager._middlewares) diff --git a/mcp/python/tests/test_openapi_config_bus_wiring.py b/mcp/python/tests/test_openapi_config_bus_wiring.py index e5a84eea..24cfda97 100644 --- a/mcp/python/tests/test_openapi_config_bus_wiring.py +++ b/mcp/python/tests/test_openapi_config_bus_wiring.py @@ -80,14 +80,14 @@ class TestApcoreMcpOpenapiConfigBusOnly: def test_none_backend_with_openapi_config_builds_server(self) -> None: fake_cfg = _FakeConfig({"mcp.openapi": {"spec": _PETSTORE}}) - with patch("apcore.Config") as mock_cfg_cls: + with patch("apcore.config.Config") as mock_cfg_cls: mock_cfg_cls.load.return_value = fake_cfg mcp = APCoreMCP(None, name="test") assert "list_pets" in mcp.tools def test_none_backend_with_no_config_raises(self) -> None: fake_cfg = _FakeConfig({}) - with patch("apcore.Config") as mock_cfg_cls: + with patch("apcore.config.Config") as mock_cfg_cls: mock_cfg_cls.load.return_value = fake_cfg with pytest.raises(ValueError, match="extensions_dir_or_backend is required"): APCoreMCP(None, name="test") @@ -96,7 +96,7 @@ def test_explicit_backend_plus_openapi_config_requires_prefix(self) -> None: from apcore import Registry fake_cfg = _FakeConfig({"mcp.openapi": {"spec": _PETSTORE}}) - with patch("apcore.Config") as mock_cfg_cls: + with patch("apcore.config.Config") as mock_cfg_cls: mock_cfg_cls.load.return_value = fake_cfg with pytest.raises(ValueError, match="mcp.openapi.prefix is required"): APCoreMCP(Registry(), name="test") @@ -105,7 +105,7 @@ def test_explicit_backend_plus_openapi_config_with_prefix_unions(self) -> None: from apcore import Registry fake_cfg = _FakeConfig({"mcp.openapi": {"spec": _PETSTORE, "prefix": "petstore"}}) - with patch("apcore.Config") as mock_cfg_cls: + with patch("apcore.config.Config") as mock_cfg_cls: mock_cfg_cls.load.return_value = fake_cfg mcp = APCoreMCP(Registry(), name="test") assert "petstore.list_pets" in mcp.tools diff --git a/mcp/python/tests/test_review_fixes.py b/mcp/python/tests/test_review_fixes.py index af9a3f3d..bccd624c 100644 --- a/mcp/python/tests/test_review_fixes.py +++ b/mcp/python/tests/test_review_fixes.py @@ -617,8 +617,8 @@ def fake_config_get(key: str, default: object = None) -> object: mock_config.get.side_effect = fake_config_get with ( - patch("apcore.Config") as mock_config_cls, - patch("apcore.build_strategy_from_config", return_value=None), + patch("apcore.config.Config") as mock_config_cls, + patch("apcore.pipeline_config.build_strategy_from_config", return_value=None), patch("apcore_mcp.MCPServerFactory") as mock_fac, patch("apcore_mcp.ExecutionRouter"), patch("apcore_mcp.TransportManager") as mock_tm_cls, @@ -659,8 +659,8 @@ def fake_config_get(key: str, default: object = None) -> object: mock_config.get.side_effect = fake_config_get with ( - patch("apcore.Config") as mock_config_cls, - patch("apcore.build_strategy_from_config", return_value=None), + patch("apcore.config.Config") as mock_config_cls, + patch("apcore.pipeline_config.build_strategy_from_config", return_value=None), patch("apcore_mcp.MCPServerFactory") as mock_fac, patch("apcore_mcp.ExecutionRouter"), patch("apcore_mcp.TransportManager") as mock_tm_cls, @@ -740,7 +740,7 @@ def fake_config_get(key: str, default: object = None) -> object: mock_app = MagicMock() with ( - patch("apcore.Config") as mock_config_cls, + patch("apcore.config.Config") as mock_config_cls, patch("apcore_mcp.MCPServerFactory") as mock_fac, patch("apcore_mcp.ExecutionRouter"), patch("apcore_mcp.TransportManager") as mock_tm_cls, diff --git a/mcp/python/tests/test_stdio_isolation.py b/mcp/python/tests/test_stdio_isolation.py index 756cb327..54b62f30 100644 --- a/mcp/python/tests/test_stdio_isolation.py +++ b/mcp/python/tests/test_stdio_isolation.py @@ -143,7 +143,7 @@ class Registry: def __init__(self, **kwargs): print('registry constructor') def discover(self): print('discovery'); return 1 sys.argv = ['apcore-mcp', '--extensions-dir', {str(tmp_path)!r}] - with (patch('apcore_mcp.__main__.Registry', Registry), + with (patch('apcore.discovery.Registry', Registry), patch('apcore_mcp.__main__.serve', lambda *a, **k: print('serve'))): main() print('restored') diff --git a/mcp/rust/Cargo.lock b/mcp/rust/Cargo.lock index 9582bd20..26e107f0 100644 --- a/mcp/rust/Cargo.lock +++ b/mcp/rust/Cargo.lock @@ -98,9 +98,9 @@ dependencies = [ [[package]] name = "apcore" -version = "1.0.0-alpha.1" +version = "1.0.0-alpha.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bbc1db3680f3d81b7096fa5eb70476a2c043b333681c2a7bba3597a49bbf11f6" +checksum = "54e630a6f3c82ee9e01aec1f58ad14a06e21d8082414a1f4d398bce2f45b4de3" dependencies = [ "async-stream", "async-trait", @@ -109,7 +109,6 @@ dependencies = [ "futures-core", "futures-util", "jsonschema 0.28.3", - "notify", "parking_lot", "referencing 0.28.3", "regex", @@ -126,7 +125,7 @@ dependencies = [ [[package]] name = "apcore-mcp" -version = "0.23.5-alpha.1" +version = "0.23.5-alpha.2" dependencies = [ "apcore", "apcore-toolkit", @@ -164,9 +163,9 @@ dependencies = [ [[package]] name = "apcore-toolkit" -version = "0.15.1-alpha.1" +version = "0.15.1-alpha.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7054dcf35f7f9f0823f3118f3ab531a511cca25d6c2f07cdc7c222de10bf0673" +checksum = "8c073619a002dcf93c6391a22c537420b86f3863dd3eef7b6cc9ebbec712c146" dependencies = [ "apcore", "async-trait", @@ -875,15 +874,6 @@ dependencies = [ "num", ] -[[package]] -name = "fsevent-sys" -version = "4.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "76ee7a02da4d231650c7cea31349b889be2f45ddb3ef3032d2ec8185f6313fd2" -dependencies = [ - "libc", -] - [[package]] name = "futures" version = "0.3.34" @@ -1365,26 +1355,6 @@ dependencies = [ "hashbrown 0.17.2", ] -[[package]] -name = "inotify" -version = "0.11.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "153be1941a183ec9ccd095ddbe17a8b8d435ef6c76e9e02451b933c3999af2c8" -dependencies = [ - "bitflags", - "inotify-sys", - "libc", -] - -[[package]] -name = "inotify-sys" -version = "0.1.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c033f80b2c113cdf91ab7a33faa9cbc014726dcad99880c8609af2a370edf37d" -dependencies = [ - "libc", -] - [[package]] name = "ipnet" version = "2.12.2" @@ -1498,26 +1468,6 @@ dependencies = [ "simple_asn1", ] -[[package]] -name = "kqueue" -version = "1.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "273c0752728918e0ac4976f2b275b6fefb9ecd400585dec929419f3844cd87b5" -dependencies = [ - "kqueue-sys", - "libc", -] - -[[package]] -name = "kqueue-sys" -version = "1.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "07293a4e297ac234359b510362495713f75ea345d5307140414f20c69ffeb087" -dependencies = [ - "bitflags", - "libc", -] - [[package]] name = "lazy_static" version = "1.5.1" @@ -1639,7 +1589,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "20521a903f02b0a573cd6840e9d0a5a0cc043d361fe924092cd70f8556cc9c4a" dependencies = [ "libc", - "log", "wasi", "windows-sys 0.61.2", ] @@ -1661,33 +1610,6 @@ dependencies = [ "tempfile", ] -[[package]] -name = "notify" -version = "8.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4d3d07927151ff8575b7087f245456e549fea62edf0ec4e565a5ee50c8402bc3" -dependencies = [ - "bitflags", - "fsevent-sys", - "inotify", - "kqueue", - "libc", - "log", - "mio", - "notify-types", - "walkdir", - "windows-sys 0.60.2", -] - -[[package]] -name = "notify-types" -version = "2.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "42b8cfee0e339a0337359f3c88165702ac6e600dc01c0cc9579a92d62b08477a" -dependencies = [ - "bitflags", -] - [[package]] name = "nu-ansi-term" version = "0.50.3" @@ -3362,16 +3284,7 @@ version = "0.52.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" dependencies = [ - "windows-targets 0.52.6", -] - -[[package]] -name = "windows-sys" -version = "0.60.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb" -dependencies = [ - "windows-targets 0.53.5", + "windows-targets", ] [[package]] @@ -3389,31 +3302,14 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" dependencies = [ - "windows_aarch64_gnullvm 0.52.6", - "windows_aarch64_msvc 0.52.6", - "windows_i686_gnu 0.52.6", - "windows_i686_gnullvm 0.52.6", - "windows_i686_msvc 0.52.6", - "windows_x86_64_gnu 0.52.6", - "windows_x86_64_gnullvm 0.52.6", - "windows_x86_64_msvc 0.52.6", -] - -[[package]] -name = "windows-targets" -version = "0.53.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4945f9f551b88e0d65f3db0bc25c33b8acea4d9e41163edf90dcd0b19f9069f3" -dependencies = [ - "windows-link", - "windows_aarch64_gnullvm 0.53.1", - "windows_aarch64_msvc 0.53.1", - "windows_i686_gnu 0.53.1", - "windows_i686_gnullvm 0.53.1", - "windows_i686_msvc 0.53.1", - "windows_x86_64_gnu 0.53.1", - "windows_x86_64_gnullvm 0.53.1", - "windows_x86_64_msvc 0.53.1", + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", ] [[package]] @@ -3422,96 +3318,48 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" -[[package]] -name = "windows_aarch64_gnullvm" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a9d8416fa8b42f5c947f8482c43e7d89e73a173cead56d044f6a56104a6d1b53" - [[package]] name = "windows_aarch64_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" -[[package]] -name = "windows_aarch64_msvc" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b9d782e804c2f632e395708e99a94275910eb9100b2114651e04744e9b125006" - [[package]] name = "windows_i686_gnu" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" -[[package]] -name = "windows_i686_gnu" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "960e6da069d81e09becb0ca57a65220ddff016ff2d6af6a223cf372a506593a3" - [[package]] name = "windows_i686_gnullvm" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" -[[package]] -name = "windows_i686_gnullvm" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fa7359d10048f68ab8b09fa71c3daccfb0e9b559aed648a8f95469c27057180c" - [[package]] name = "windows_i686_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" -[[package]] -name = "windows_i686_msvc" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e7ac75179f18232fe9c285163565a57ef8d3c89254a30685b57d83a38d326c2" - [[package]] name = "windows_x86_64_gnu" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" -[[package]] -name = "windows_x86_64_gnu" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c3842cdd74a865a8066ab39c8a7a473c0778a3f29370b5fd6b4b9aa7df4a499" - [[package]] name = "windows_x86_64_gnullvm" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" -[[package]] -name = "windows_x86_64_gnullvm" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0ffa179e2d07eee8ad8f57493436566c7cc30ac536a3379fdf008f47f6bb7ae1" - [[package]] name = "windows_x86_64_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" -[[package]] -name = "windows_x86_64_msvc" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650" - [[package]] name = "wit-bindgen" version = "0.51.0" diff --git a/mcp/rust/Cargo.toml b/mcp/rust/Cargo.toml index b093403e..db23c9fb 100644 --- a/mcp/rust/Cargo.toml +++ b/mcp/rust/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "apcore-mcp" -version = "0.23.5-alpha.1" +version = "0.23.5-alpha.2" edition = "2021" rust-version = "1.86" description = "MCP bridge for apcore — expose apcore modules as MCP tools" @@ -22,8 +22,8 @@ all-features = true rustdoc-args = ["--cfg", "docsrs"] [dependencies] -apcore = "=1.0.0-alpha.1" -apcore-toolkit = "=0.15.1-alpha.1" +apcore = { version = "=1.0.0-alpha.2", default-features = false, features = ["config", "sys-modules"] } +apcore-toolkit = "=0.15.1-alpha.2" mcp-embedded-ui = "0.5" tokio = { version = "1", features = ["full"] } serde = { version = "1", features = ["derive"] } diff --git a/mcp/rust/src/adapters/schema.rs b/mcp/rust/src/adapters/schema.rs index 45e1a9d2..1edca847 100644 --- a/mcp/rust/src/adapters/schema.rs +++ b/mcp/rust/src/adapters/schema.rs @@ -65,6 +65,16 @@ impl SchemaConverter { Self::convert_schema_with(schema, strict) } + /// Copy an input schema for a provider that supports recursive references. + pub(crate) fn copy_referenced_input_schema(schema: &Value) -> Value { + if schema.is_null() || schema.as_object().is_some_and(|map| map.is_empty()) { + return json!({"type": "object", "properties": {}}); + } + let mut copied = schema.clone(); + Self::ensure_object_type(&mut copied); + copied + } + fn convert_schema_with(schema: &Value, strict: bool) -> Result { // Clone to avoid mutating input let mut schema = schema.clone(); diff --git a/mcp/rust/src/apcore_mcp.rs b/mcp/rust/src/apcore_mcp.rs index 9f657f9d..4c755db9 100644 --- a/mcp/rust/src/apcore_mcp.rs +++ b/mcp/rust/src/apcore_mcp.rs @@ -2202,7 +2202,7 @@ impl Default for AsyncServeConfig { } /// Configuration for the convenience [`to_openai_tools`] function. -#[derive(Debug, Clone, Default)] +#[derive(Debug, Clone)] pub struct OpenAIToolsConfig { /// Embed annotation metadata in tool descriptions. pub embed_annotations: bool, @@ -2214,6 +2214,17 @@ pub struct OpenAIToolsConfig { pub prefix: Option, } +impl Default for OpenAIToolsConfig { + fn default() -> Self { + Self { + embed_annotations: false, + strict: true, + tags: None, + prefix: None, + } + } +} + /// Convenience: build and serve in one call (blocking). /// /// Constructs an [`APCoreMCP`] internally from the given backend source @@ -4248,7 +4259,7 @@ mod tests { fn convenience_openai_tools_config_has_defaults() { let cfg = OpenAIToolsConfig::default(); assert!(!cfg.embed_annotations); - assert!(!cfg.strict); + assert!(cfg.strict); assert!(cfg.tags.is_none()); assert!(cfg.prefix.is_none()); } diff --git a/mcp/rust/src/converters/anthropic.rs b/mcp/rust/src/converters/anthropic.rs new file mode 100644 index 00000000..daa51bb5 --- /dev/null +++ b/mcp/rust/src/converters/anthropic.rs @@ -0,0 +1,35 @@ +//! Project APCore module descriptors into Anthropic Messages tools. + +use apcore::registry::ModuleDescriptor; +use serde_json::{json, Value}; + +use crate::adapters::{AdapterError, ModuleIDNormalizer}; + +use super::prepare_llm_schema; + +/// Convert one module descriptor to an Anthropic Messages tool. +#[derive(Default)] +pub struct AnthropicConverter; + +impl AnthropicConverter { + /// Preserve input constraints and include the descriptor's input examples. + pub fn convert_descriptor(&self, descriptor: &ModuleDescriptor) -> Result { + let mut schema = descriptor.input_schema.clone(); + prepare_llm_schema(&mut schema, true); + let mut tool = json!({ + "name": ModuleIDNormalizer::normalize(&descriptor.module_id)?, + "description": descriptor.description, + "input_schema": schema, + }); + if !descriptor.examples.is_empty() { + tool["input_examples"] = Value::Array( + descriptor + .examples + .iter() + .map(|example| example.inputs.clone()) + .collect(), + ); + } + Ok(tool) + } +} diff --git a/mcp/rust/src/converters/mod.rs b/mcp/rust/src/converters/mod.rs index 0bfba8e3..c91d5dd4 100644 --- a/mcp/rust/src/converters/mod.rs +++ b/mcp/rust/src/converters/mod.rs @@ -1,6 +1,62 @@ //! Converters sub-module — convert apcore registries to external tool formats. +pub mod anthropic; pub mod openai; // ---- Re-exports ------------------------------------------------------------- +pub use anthropic::AnthropicConverter; pub use openai::{ConverterError, OpenAIConverter}; + +use serde_json::Value; + +fn prepare_llm_schema(schema: &mut Value, strip_extensions: bool) { + let Some(schema) = schema.as_object_mut() else { + return; + }; + if let Some(description) = schema + .get("x-llm-description") + .filter(|value| value.is_string()) + { + schema.insert("description".to_owned(), description.clone()); + } + if strip_extensions { + schema.retain(|key, _| !key.starts_with("x-")); + } + for key in [ + "properties", + "patternProperties", + "$defs", + "definitions", + "dependentSchemas", + ] { + if let Some(children) = schema.get_mut(key).and_then(Value::as_object_mut) { + for child in children.values_mut() { + prepare_llm_schema(child, strip_extensions); + } + } + } + for key in ["oneOf", "anyOf", "allOf", "prefixItems", "items"] { + if let Some(children) = schema.get_mut(key) { + if let Some(children) = children.as_array_mut() { + for child in children { + prepare_llm_schema(child, strip_extensions); + } + } else if key == "items" { + prepare_llm_schema(children, strip_extensions); + } + } + } + for key in [ + "not", + "if", + "then", + "else", + "contains", + "propertyNames", + "additionalProperties", + ] { + if let Some(child) = schema.get_mut(key) { + prepare_llm_schema(child, strip_extensions); + } + } +} diff --git a/mcp/rust/src/converters/openai.rs b/mcp/rust/src/converters/openai.rs index d4489adf..5f24d5d1 100644 --- a/mcp/rust/src/converters/openai.rs +++ b/mcp/rust/src/converters/openai.rs @@ -4,9 +4,11 @@ use std::collections::HashMap; use apcore::module::{ModuleAnnotations, ModuleExample}; use apcore::registry::registry::Registry; +use apcore::schema::to_strict_schema; use apcore_toolkit::ScannedModule; use serde_json::Value; +use super::prepare_llm_schema; use crate::adapters::{AdapterError, AnnotationMapper, ModuleIDNormalizer, SchemaConverter}; use crate::markdown; @@ -47,7 +49,7 @@ pub enum ConverterError { /// (currently `rich_description`, future possibilities like /// `embed_examples`, `compact_schema`) doesn't ratchet the positional /// signature of every public method. -#[derive(Debug, Clone, Default)] +#[derive(Debug, Clone)] pub struct ConvertOptions { /// Append annotation hints (e.g. `[idempotent]`) to the description. pub embed_annotations: bool, @@ -61,8 +63,18 @@ pub struct ConvertOptions { pub rich_description: bool, } +impl Default for ConvertOptions { + fn default() -> Self { + Self { + embed_annotations: false, + strict: true, + rich_description: false, + } + } +} + impl ConvertOptions { - /// Construct with all flags off (same as `Default`). + /// Construct with strict mode enabled and other options disabled. pub fn new() -> Self { Self::default() } @@ -408,7 +420,7 @@ impl OpenAIConverter { .unwrap_or(Value::Null); // OpenAI converter keeps legacy (non-strict) behavior; callers can // opt-in separately. MCP tool schemas in factory.rs use strict mode. - let mut parameters = SchemaConverter::convert_input_schema_strict(&input_schema, false)?; + let mut parameters = SchemaConverter::copy_referenced_input_schema(&input_schema); // Resolve the LLM-facing description. `rich_description` swaps // the supplied plain description for a Markdown body rendered @@ -458,6 +470,35 @@ impl OpenAIConverter { })) } + /// Convert one module to a Responses API function tool. + pub fn convert_responses_descriptor( + &self, + name: &str, + descriptor: &Value, + description: &str, + options: ConvertOptions, + ) -> Result { + let strict = options.strict; + let chat = self.convert_descriptor_with_options(name, descriptor, description, options)?; + Ok(responses_tool(chat, strict)) + } + + /// Convert a registry to Responses API function tools. + pub fn convert_responses_registry( + &self, + registry: &Registry, + options: ConvertOptions, + tags: Option<&[&str]>, + prefix: Option<&str>, + ) -> Result, ConverterError> { + let strict = options.strict; + Ok(self + .convert_registry_with_options(registry, options, tags, prefix)? + .into_iter() + .map(|chat| responses_tool(chat, strict)) + .collect()) + } + // ---- Strict mode helpers (private) -------------------------------------- /// Apply OpenAI strict mode transformations to a schema. @@ -468,192 +509,8 @@ impl OpenAIConverter { /// properties required, optional properties become nullable). fn apply_strict_mode(schema: &Value) -> Value { let mut schema = schema.clone(); - Self::apply_llm_descriptions(&mut schema); - Self::strip_extensions(&mut schema); - Self::convert_to_strict(&mut schema); - schema - } - - /// Promote `x-llm-description` to `description` recursively. - /// - /// [A-D-OC-3] Promotion is unconditional: spec step 1 pins - /// "Promote `x-llm-description` -> `description` (before stripping)" with - /// no precondition, and TypeScript promotes whenever the key holds a - /// string. Guarding on an existing `description` meant step 2's `x-*` - /// strip silently discarded the text on nodes annotated only with - /// `x-llm-description`. - /// - /// The walk is generic rather than a keyword whitelist, matching both - /// TypeScript and [`Self::strip_extensions`] in this same pipeline — a - /// narrower walk here would let the strip remove an annotation this pass - /// never saw. - fn apply_llm_descriptions(node: &mut Value) { - match node { - Value::Object(map) => { - // Only string values are promotable, as TypeScript's - // `typeof obj["x-llm-description"] === "string"` guard requires. - if let Some(llm_desc) = map.get("x-llm-description").and_then(Value::as_str) { - let llm_desc = llm_desc.to_string(); - map.insert("description".to_string(), Value::String(llm_desc)); - } - for value in map.values_mut() { - Self::apply_llm_descriptions(value); - } - } - Value::Array(arr) => { - for item in arr.iter_mut() { - Self::apply_llm_descriptions(item); - } - } - _ => {} - } - } - - /// Remove all `x-*` keys and `default` keys recursively. - fn strip_extensions(node: &mut Value) { - match node { - Value::Object(map) => { - // Remove x-* and default keys - map.retain(|k, _| !k.starts_with("x-") && k != "default"); - // Recurse into all remaining values - for value in map.values_mut() { - Self::strip_extensions(value); - } - } - Value::Array(arr) => { - for item in arr.iter_mut() { - Self::strip_extensions(item); - } - } - _ => {} - } - } - - /// Enforce strict mode rules on an object schema. Mutates in place. - /// - /// For objects with `properties`: - /// - Sets `additionalProperties: false` - /// - Identifies optional properties (not already in `required`) - /// - Makes optional properties nullable (type array or oneOf wrapping) - /// - Sets `required` to sorted list of all property names - /// - /// Recurses into properties, items, oneOf/anyOf/allOf, $defs/definitions. - fn convert_to_strict(node: &mut Value) { - let obj = match node.as_object_mut() { - Some(o) => o, - None => return, - }; - - // Process object schemas with properties - if obj.get("type") == Some(&Value::String("object".to_string())) - && obj.contains_key("properties") - { - // Set additionalProperties: false - obj.insert("additionalProperties".to_string(), Value::Bool(false)); - - // Collect existing required set - let existing_required: std::collections::HashSet = obj - .get("required") - .and_then(|v| v.as_array()) - .map(|arr| { - arr.iter() - .filter_map(|v| v.as_str().map(String::from)) - .collect() - }) - .unwrap_or_default(); - - // Get all property names - let all_names: Vec = obj - .get("properties") - .and_then(|v| v.as_object()) - .map(|props| props.keys().cloned().collect()) - .unwrap_or_default(); - - // Identify optional properties - let optional_names: Vec = all_names - .iter() - .filter(|n| !existing_required.contains(n.as_str())) - .cloned() - .collect(); - - // Make optional properties nullable - if let Some(Value::Object(props)) = obj.get_mut("properties") { - for name in &optional_names { - if let Some(prop) = props.get_mut(name) { - Self::make_nullable(prop); - } - } - } - - // Set required to sorted list of all property names - let mut sorted_names = all_names; - sorted_names.sort(); - obj.insert( - "required".to_string(), - Value::Array(sorted_names.into_iter().map(Value::String).collect()), - ); - } - - // Recurse into properties - if let Some(Value::Object(props)) = obj.get_mut("properties") { - for prop in props.values_mut() { - Self::convert_to_strict(prop); - } - } - - // Recurse into items - if let Some(items) = obj.get_mut("items") { - if items.is_object() { - Self::convert_to_strict(items); - } - } - - // Recurse into oneOf/anyOf/allOf - for keyword in &["oneOf", "anyOf", "allOf"] { - if let Some(Value::Array(arr)) = obj.get_mut(*keyword) { - for sub in arr.iter_mut() { - Self::convert_to_strict(sub); - } - } - } - - // Recurse into $defs/definitions - for defs_key in &["$defs", "definitions"] { - if let Some(Value::Object(defs)) = obj.get_mut(*defs_key) { - for defn in defs.values_mut() { - Self::convert_to_strict(defn); - } - } - } - } - - /// Make a property nullable by modifying its type or wrapping in oneOf. - fn make_nullable(prop: &mut Value) { - if let Some(obj) = prop.as_object_mut() { - if let Some(type_val) = obj.get_mut("type") { - match type_val { - Value::String(s) => { - // "string" -> ["string", "null"] - let original = s.clone(); - *type_val = Value::Array(vec![ - Value::String(original), - Value::String("null".to_string()), - ]); - } - Value::Array(arr) if !arr.contains(&Value::String("null".to_string())) => { - // ["string", "integer"] -> ["string", "integer", "null"] - arr.push(Value::String("null".to_string())); - } - _ => {} - } - } else { - // No type key (pure $ref or composition) — wrap in oneOf with null - let original = prop.clone(); - *prop = serde_json::json!({ - "oneOf": [original, {"type": "null"}] - }); - } - } + prepare_llm_schema(&mut schema, false); + to_strict_schema(&schema) } } @@ -663,6 +520,13 @@ impl Default for OpenAIConverter { } } +fn responses_tool(mut chat: Value, strict: bool) -> Value { + let mut tool = chat["function"].take(); + tool["type"] = Value::String("function".to_owned()); + tool["strict"] = Value::Bool(strict); + tool +} + // ---- JSON → ScannedModule adapter ------------------------------------------- /// Project a JSON entry from the duck-typed registry-as-JSON form @@ -792,310 +656,6 @@ mod tests { // Default impl works without panic } - // ---- Task 2: strict-mode tests ------------------------------------------ - - // ---- apply_llm_descriptions tests ---- - - #[test] - fn test_apply_llm_descriptions_replaces_description() { - let mut node = json!({ - "description": "Original", - "x-llm-description": "LLM version" - }); - OpenAIConverter::apply_llm_descriptions(&mut node); - assert_eq!(node["description"], "LLM version"); - } - - #[test] - fn test_apply_llm_descriptions_preserves_when_no_llm() { - let mut node = json!({ - "description": "Original" - }); - OpenAIConverter::apply_llm_descriptions(&mut node); - assert_eq!(node["description"], "Original"); - } - - #[test] - fn test_apply_llm_descriptions_nested_properties() { - let mut node = json!({ - "type": "object", - "properties": { - "name": { - "description": "Old", - "x-llm-description": "New" - } - } - }); - OpenAIConverter::apply_llm_descriptions(&mut node); - assert_eq!(node["properties"]["name"]["description"], "New"); - } - - #[test] - fn test_apply_llm_descriptions_nested_items() { - let mut node = json!({ - "type": "array", - "items": { - "description": "Old", - "x-llm-description": "New" - } - }); - OpenAIConverter::apply_llm_descriptions(&mut node); - assert_eq!(node["items"]["description"], "New"); - } - - #[test] - fn test_apply_llm_descriptions_nested_oneof() { - let mut node = json!({ - "oneOf": [ - {"description": "A", "x-llm-description": "A-LLM"}, - {"description": "B"} - ] - }); - OpenAIConverter::apply_llm_descriptions(&mut node); - assert_eq!(node["oneOf"][0]["description"], "A-LLM"); - assert_eq!(node["oneOf"][1]["description"], "B"); - } - - #[test] - fn test_apply_llm_descriptions_nested_defs() { - let mut node = json!({ - "$defs": { - "Foo": { - "description": "Old", - "x-llm-description": "New" - } - }, - "definitions": { - "Bar": { - "description": "Old", - "x-llm-description": "New" - } - } - }); - OpenAIConverter::apply_llm_descriptions(&mut node); - assert_eq!(node["$defs"]["Foo"]["description"], "New"); - assert_eq!(node["definitions"]["Bar"]["description"], "New"); - } - - // ---- strip_extensions tests ---- - - #[test] - fn test_strip_extensions_removes_x_keys() { - let mut node = json!({ - "type": "string", - "x-custom": "value", - "x-another": 42 - }); - OpenAIConverter::strip_extensions(&mut node); - assert!(node.get("x-custom").is_none()); - assert!(node.get("x-another").is_none()); - assert_eq!(node["type"], "string"); - } - - #[test] - fn test_strip_extensions_removes_defaults() { - let mut node = json!({ - "type": "string", - "default": "hello" - }); - OpenAIConverter::strip_extensions(&mut node); - assert!(node.get("default").is_none()); - assert_eq!(node["type"], "string"); - } - - #[test] - fn test_strip_extensions_recursive() { - let mut node = json!({ - "type": "object", - "properties": { - "name": { - "type": "string", - "x-custom": "remove", - "default": "val" - } - }, - "items": { - "x-ext": true - } - }); - OpenAIConverter::strip_extensions(&mut node); - assert!(node["properties"]["name"].get("x-custom").is_none()); - assert!(node["properties"]["name"].get("default").is_none()); - assert!(node["items"].get("x-ext").is_none()); - } - - #[test] - fn test_strip_extensions_preserves_non_x_keys() { - let mut node = json!({ - "type": "string", - "description": "keep", - "enum": ["a", "b"], - "x-remove": true - }); - OpenAIConverter::strip_extensions(&mut node); - assert_eq!(node["type"], "string"); - assert_eq!(node["description"], "keep"); - assert_eq!(node["enum"], json!(["a", "b"])); - assert!(node.get("x-remove").is_none()); - } - - // ---- convert_to_strict tests ---- - - #[test] - fn test_convert_to_strict_sets_additional_properties_false() { - let mut node = json!({ - "type": "object", - "properties": { - "name": {"type": "string"} - } - }); - OpenAIConverter::convert_to_strict(&mut node); - assert_eq!(node["additionalProperties"], false); - } - - #[test] - fn test_convert_to_strict_makes_all_required() { - let mut node = json!({ - "type": "object", - "properties": { - "zebra": {"type": "string"}, - "alpha": {"type": "integer"} - } - }); - OpenAIConverter::convert_to_strict(&mut node); - assert_eq!(node["required"], json!(["alpha", "zebra"])); - } - - #[test] - fn test_convert_to_strict_nullable_optional_string() { - let mut node = json!({ - "type": "object", - "properties": { - "name": {"type": "string"} - } - }); - OpenAIConverter::convert_to_strict(&mut node); - assert_eq!( - node["properties"]["name"]["type"], - json!(["string", "null"]) - ); - } - - #[test] - fn test_convert_to_strict_nullable_optional_array_type() { - let mut node = json!({ - "type": "object", - "properties": { - "value": {"type": ["string", "integer"]} - } - }); - OpenAIConverter::convert_to_strict(&mut node); - assert_eq!( - node["properties"]["value"]["type"], - json!(["string", "integer", "null"]) - ); - } - - #[test] - fn test_convert_to_strict_nullable_optional_ref() { - let mut node = json!({ - "type": "object", - "properties": { - "config": {"$ref": "#/$defs/Config"} - } - }); - OpenAIConverter::convert_to_strict(&mut node); - let config = &node["properties"]["config"]; - assert!(config.get("oneOf").is_some()); - let one_of = config["oneOf"].as_array().unwrap(); - assert_eq!(one_of.len(), 2); - assert_eq!(one_of[0], json!({"$ref": "#/$defs/Config"})); - assert_eq!(one_of[1], json!({"type": "null"})); - } - - #[test] - fn test_convert_to_strict_preserves_required() { - let mut node = json!({ - "type": "object", - "properties": { - "required_field": {"type": "string"}, - "optional_field": {"type": "integer"} - }, - "required": ["required_field"] - }); - OpenAIConverter::convert_to_strict(&mut node); - // required_field should NOT become nullable (it was already required) - assert_eq!(node["properties"]["required_field"]["type"], "string"); - // optional_field SHOULD become nullable - assert_eq!( - node["properties"]["optional_field"]["type"], - json!(["integer", "null"]) - ); - // Both should be in required now - assert_eq!( - node["required"], - json!(["optional_field", "required_field"]) - ); - } - - #[test] - fn test_convert_to_strict_recursive_nested_object() { - // When inner is already required, its type stays "object" and recursion applies - let mut node = json!({ - "type": "object", - "properties": { - "inner": { - "type": "object", - "properties": { - "value": {"type": "string"} - } - } - }, - "required": ["inner"] - }); - OpenAIConverter::convert_to_strict(&mut node); - // inner was required so type stays "object", recursion applies strict rules - assert_eq!(node["properties"]["inner"]["additionalProperties"], false); - assert_eq!( - node["properties"]["inner"]["properties"]["value"]["type"], - json!(["string", "null"]) - ); - assert_eq!(node["properties"]["inner"]["required"], json!(["value"])); - } - - #[test] - fn test_convert_to_strict_recursive_items() { - let mut node = json!({ - "type": "array", - "items": { - "type": "object", - "properties": { - "id": {"type": "integer"} - } - } - }); - OpenAIConverter::convert_to_strict(&mut node); - assert_eq!(node["items"]["additionalProperties"], false); - assert_eq!(node["items"]["required"], json!(["id"])); - } - - #[test] - fn test_convert_to_strict_recursive_oneof() { - let mut node = json!({ - "oneOf": [ - { - "type": "object", - "properties": { - "a": {"type": "string"} - } - } - ] - }); - OpenAIConverter::convert_to_strict(&mut node); - assert_eq!(node["oneOf"][0]["additionalProperties"], false); - assert_eq!(node["oneOf"][0]["required"], json!(["a"])); - } - // ---- apply_strict_mode end-to-end test ---- #[test] @@ -1168,74 +728,6 @@ mod tests { ); } - // ---- Edge cases ---- - - #[test] - fn test_strip_extensions_array_with_objects() { - let mut node = json!({ - "oneOf": [ - {"type": "string", "x-ext": true}, - {"type": "integer", "default": 0} - ] - }); - OpenAIConverter::strip_extensions(&mut node); - assert!(node["oneOf"][0].get("x-ext").is_none()); - assert!(node["oneOf"][1].get("default").is_none()); - } - - #[test] - fn test_convert_to_strict_no_properties_no_change() { - let mut node = json!({"type": "string"}); - let original = node.clone(); - OpenAIConverter::convert_to_strict(&mut node); - assert_eq!(node, original); - } - - /// [A-D-OC-3] Promotion is unconditional. Spec step 1 pins - /// "Promote `x-llm-description` -> `description` (before stripping)" with - /// no precondition, and TypeScript promotes whenever the key holds a - /// string. Requiring an existing `description` meant step 2's `x-*` strip - /// silently discarded the text on a node annotated only with - /// `x-llm-description`. - #[test] - fn test_apply_llm_descriptions_without_existing_description_key() { - let mut node = json!({ - "x-llm-description": "LLM only" - }); - OpenAIConverter::apply_llm_descriptions(&mut node); - assert_eq!(node["description"], "LLM only"); - } - - /// [A-D-OC-3] Non-string values are not promoted — TypeScript guards with - /// `typeof obj["x-llm-description"] === "string"`. - #[test] - fn test_apply_llm_descriptions_ignores_non_string() { - let mut node = json!({"x-llm-description": 42}); - OpenAIConverter::apply_llm_descriptions(&mut node); - assert!(node.get("description").is_none()); - } - - /// [A-D-OC-3] The keyed walk visited only - /// properties/items/oneOf/anyOf/allOf/$defs/definitions, so nodes reached - /// through any other keyword were promoted in TypeScript and not in Rust — - /// and then stripped, losing the text entirely. - #[test] - fn test_apply_llm_descriptions_reaches_non_whitelisted_keywords() { - let mut node = json!({ - "type": "object", - "patternProperties": { - "^a": {"type": "string", "x-llm-description": "pattern doc"} - }, - "prefixItems": [{"type": "string", "x-llm-description": "prefix doc"}] - }); - OpenAIConverter::apply_llm_descriptions(&mut node); - assert_eq!( - node["patternProperties"]["^a"]["description"], - "pattern doc" - ); - assert_eq!(node["prefixItems"][0]["description"], "prefix doc"); - } - /// End-to-end through strict conversion: a property carrying ONLY /// `x-llm-description` keeps that text as `description`. #[test] @@ -1254,22 +746,6 @@ mod tests { assert!(result["properties"]["q"].get("x-llm-description").is_none()); } - #[test] - fn test_convert_to_strict_already_nullable_not_doubled() { - let mut node = json!({ - "type": "object", - "properties": { - "value": {"type": ["string", "null"]} - } - }); - OpenAIConverter::convert_to_strict(&mut node); - // Should not add another "null" - assert_eq!( - node["properties"]["value"]["type"], - json!(["string", "null"]) - ); - } - // ---- Task 3: convert-descriptor tests ----------------------------------- #[test] diff --git a/mcp/rust/src/lib.rs b/mcp/rust/src/lib.rs index 720fa228..e4207a17 100644 --- a/mcp/rust/src/lib.rs +++ b/mcp/rust/src/lib.rs @@ -77,6 +77,7 @@ pub use crate::config::{mcp_defaults, register_mcp_namespace, MCP_ENV_PREFIX, MC // ---- Re-exports: converters ------------------------------------------------- pub use crate::converters::openai::{ConvertOptions, ConverterError, OpenAIConverter}; +pub use crate::converters::AnthropicConverter; // ---- Re-exports: helpers ---------------------------------------------------- pub use crate::helpers::{elicit, report_progress, ElicitResult, MCP_ELICIT_KEY, MCP_PROGRESS_KEY}; diff --git a/mcp/rust/tests/converters_test.rs b/mcp/rust/tests/converters_test.rs index fe8437f3..4d850da5 100644 --- a/mcp/rust/tests/converters_test.rs +++ b/mcp/rust/tests/converters_test.rs @@ -2,8 +2,88 @@ mod common; -use apcore_mcp::{OpenAIConverter, SchemaConverter}; -use serde_json::json; +use apcore::module::ModuleAnnotations; +use apcore::registry::ModuleDescriptor; +use apcore_mcp::server::factory::MCPServerFactory; +use apcore_mcp::{AnthropicConverter, ConvertOptions, OpenAIConverter, SchemaConverter}; +use serde_json::{json, Value}; + +#[test] +fn matches_the_shared_provider_tool_projection() { + let Some(fixture) = common::load_fixture::("tool_projection.json") else { + return; + }; + let module = &fixture["module"]; + let id = module["module_id"].as_str().unwrap(); + let description = module["description"].as_str().unwrap(); + let mut descriptor: ModuleDescriptor = serde_json::from_value(module.clone()).unwrap(); + let expected = &fixture["expected"]; + let openai = OpenAIConverter::new(); + let default_chat = openai + .convert_descriptor_with_options(id, module, description, ConvertOptions::default()) + .unwrap(); + assert_eq!(default_chat, expected["openai_chat"]); + let loose_responses = openai + .convert_responses_descriptor( + id, + module, + description, + ConvertOptions::default().with_strict(false), + ) + .unwrap(); + assert_eq!(loose_responses, expected["openai_responses_non_strict"]); + let mut strict_responses = expected["openai_chat"]["function"].clone(); + strict_responses["type"] = json!("function"); + assert_eq!( + openai + .convert_responses_descriptor(id, module, description, ConvertOptions::default()) + .unwrap(), + strict_responses + ); + assert_eq!( + AnthropicConverter.convert_descriptor(&descriptor).unwrap(), + expected["anthropic"] + ); + + let factory = MCPServerFactory::new(); + descriptor.annotations = Some(ModuleAnnotations { + requires_approval: true, + streaming: true, + ..Default::default() + }); + let tool = factory.build_tool(&descriptor, description, None).unwrap(); + assert_eq!(tool.name, id); + assert_eq!(tool.input_schema, descriptor.input_schema); + assert_eq!(tool.output_schema.as_ref(), Some(&descriptor.output_schema)); + assert_eq!(tool.meta.unwrap(), expected["mcp_meta"]); + let annotations = serde_json::to_value(tool.annotations.unwrap()).unwrap(); + assert!(annotations.get("requiresApproval").is_none()); + assert!(annotations.get("streaming").is_none()); + descriptor.annotations = Some(ModuleAnnotations::default()); + assert!(factory + .build_tool(&descriptor, description, None) + .unwrap() + .meta + .is_none()); + + descriptor.input_schema = fixture["recursive_input_schema"].clone(); + assert_eq!( + AnthropicConverter.convert_descriptor(&descriptor).unwrap()["input_schema"], + descriptor.input_schema + ); + let recursive = openai + .convert_descriptor_with_options( + id, + &json!({"input_schema": descriptor.input_schema}), + description, + ConvertOptions::default(), + ) + .unwrap(); + assert_eq!( + recursive.pointer("/function/parameters/$defs/node/properties/children/items/$ref"), + Some(&json!("#/$defs/node")) + ); +} // ---- SchemaConverter roundtrip tests --------------------------------------- diff --git a/mcp/typescript/package.json b/mcp/typescript/package.json index 74a19dc6..f4a85437 100644 --- a/mcp/typescript/package.json +++ b/mcp/typescript/package.json @@ -1,6 +1,6 @@ { "name": "apcore-mcp", - "version": "0.23.9-alpha.1", + "version": "0.23.9-alpha.2", "packageManager": "pnpm@10.30.1", "description": "Automatic MCP Server & OpenAI Tools Bridge for apcore", "type": "module", @@ -51,8 +51,8 @@ "dependencies": { "@modelcontextprotocol/sdk": "1.32.0", "ajv": "^8.17.1", - "apcore-js": ">=0.33.0 <1.0.0 || 1.0.0-alpha.1", - "apcore-toolkit": "0.15.1-alpha.1", + "apcore-js": "1.0.0-alpha.2", + "apcore-toolkit": "0.15.1-alpha.2", "jsonwebtoken": ">=9.0.3", "mcp-embedded-ui": ">=0.5.1" }, diff --git a/mcp/typescript/pnpm-lock.yaml b/mcp/typescript/pnpm-lock.yaml index d178ebfb..7c4e16af 100644 --- a/mcp/typescript/pnpm-lock.yaml +++ b/mcp/typescript/pnpm-lock.yaml @@ -15,11 +15,11 @@ importers: specifier: ^8.17.1 version: 8.20.0 apcore-js: - specifier: '>=0.33.0 <1.0.0 || 1.0.0-alpha.1' - version: 0.33.0 + specifier: 1.0.0-alpha.2 + version: 1.0.0-alpha.2(typescript@5.9.3) apcore-toolkit: - specifier: 0.15.1-alpha.1 - version: 0.15.1-alpha.1(@sinclair/typebox@0.34.48) + specifier: 0.15.1-alpha.2 + version: 0.15.1-alpha.2(@sinclair/typebox@0.34.48)(typescript@5.9.3) jsonwebtoken: specifier: '>=9.0.3' version: 9.0.3 @@ -619,12 +619,17 @@ packages: resolution: {integrity: sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==} engines: {node: '>=8'} - apcore-js@0.33.0: - resolution: {integrity: sha512-+0UPovkB37qKy9kUwZmgSK6an+RqOUy+XOU9sEAauXStmQYIWmPBV7ACymQ9nwPI4RVAKiWbU4upMIqrCitxoQ==} + apcore-js@1.0.0-alpha.2: + resolution: {integrity: sha512-WnQj/V/f43e0PbYIALpvjrerv/XOJStKE+FuOEl80qYEAtKWb/pKn1ho7p11HBinc6diCBxqIGScoN7qscnsbg==} engines: {node: '>=20.0.0'} + peerDependencies: + typescript: ^5.5.0 + peerDependenciesMeta: + typescript: + optional: true - apcore-toolkit@0.15.1-alpha.1: - resolution: {integrity: sha512-e8E9gtYAKLeBkpdIQisey4LogMdTR+qffL5PD5U0TyLiVl2v90xSBVXfHof3FkJWMj0/MKRqjlyzBk750xmt+w==} + apcore-toolkit@0.15.1-alpha.2: + resolution: {integrity: sha512-nBMk99wAGjSH/E3fCj4I5FsvlvYiVs+k+ARIGc6u+kkxiTvxoAlQNKAUviBYJBrmItwDVl+9EonaEO2qfiRQGg==} engines: {node: '>=20.10.0'} peerDependencies: '@sinclair/typebox': '>=0.31.0' @@ -1933,18 +1938,22 @@ snapshots: dependencies: color-convert: 2.0.1 - apcore-js@0.33.0: + apcore-js@1.0.0-alpha.2(typescript@5.9.3): dependencies: '@sinclair/typebox': 0.34.48 js-yaml: 4.3.2 uuid: 11.1.1 + optionalDependencies: + typescript: 5.9.3 - apcore-toolkit@0.15.1-alpha.1(@sinclair/typebox@0.34.48): + apcore-toolkit@0.15.1-alpha.2(@sinclair/typebox@0.34.48)(typescript@5.9.3): dependencies: '@sinclair/typebox': 0.34.48 ajv: 8.20.0 - apcore-js: 0.33.0 + apcore-js: 1.0.0-alpha.2(typescript@5.9.3) js-yaml: 4.3.2 + transitivePeerDependencies: + - typescript apdev-js@0.2.4(typescript@5.9.3): dependencies: diff --git a/mcp/typescript/src/adapters/schema.ts b/mcp/typescript/src/adapters/schema.ts index 7cb5b03e..6cd2cf3f 100644 --- a/mcp/typescript/src/adapters/schema.ts +++ b/mcp/typescript/src/adapters/schema.ts @@ -9,6 +9,35 @@ import type { JsonSchema, ModuleDescriptor } from "../types.js"; export interface ConvertSchemaOptions { strict?: boolean; + inlineRefs?: boolean; +} + +export function prepareLlmSchema(schema: JsonSchema, stripExtensions = false): void { + if (typeof schema["x-llm-description"] === "string") { + schema.description = schema["x-llm-description"]; + } + if (stripExtensions) { + for (const key of Object.keys(schema)) { + if (key.startsWith("x-")) delete schema[key]; + } + } + const visit = (child: unknown): void => { + if (typeof child === "object" && child !== null && !Array.isArray(child)) { + prepareLlmSchema(child as JsonSchema, stripExtensions); + } + }; + for (const key of ["properties", "patternProperties", "$defs", "definitions", "dependentSchemas"]) { + const children = schema[key]; + if (typeof children === "object" && children !== null) Object.values(children).forEach(visit); + } + for (const key of ["oneOf", "anyOf", "allOf", "prefixItems", "items"]) { + const children = schema[key]; + if (Array.isArray(children)) children.forEach(visit); + else if (key === "items") visit(children); + } + for (const key of ["not", "if", "then", "else", "contains", "propertyNames", "additionalProperties"]) { + visit(schema[key]); + } } /** @@ -61,14 +90,15 @@ export class SchemaConverter { const copied = structuredClone(schema); // Extract and remove $defs before inlining - const defs = (copied["$defs"] as Record) ?? {}; - delete copied["$defs"]; - - // Inline all $ref references (with circular ref detection) - const inlined = this._inlineRefs(copied, defs, new Set(), 0) as JsonSchema; + let schemaForTarget = copied; + if (options?.inlineRefs ?? true) { + const defs = (copied["$defs"] as Record) ?? {}; + delete copied["$defs"]; + schemaForTarget = this._inlineRefs(copied, defs, new Set(), 0) as JsonSchema; + } // Ensure the top-level schema has type: "object" - const normalized = this._ensureObjectType(inlined); + const normalized = this._ensureObjectType(schemaForTarget); // [SC-11] Default strict=true to match Python and Rust SDKs. Pre-fix // TS defaulted to false (undefined → falsy), silently producing diff --git a/mcp/typescript/src/apcore-mcp.ts b/mcp/typescript/src/apcore-mcp.ts index 4cc29cff..fec0ff05 100644 --- a/mcp/typescript/src/apcore-mcp.ts +++ b/mcp/typescript/src/apcore-mcp.ts @@ -307,7 +307,7 @@ export class APCoreMCP { try { // eslint-disable-next-line @typescript-eslint/no-explicit-any - const apcore = await import("apcore-js") as any; + const apcore = await import("apcore-js/full") as any; const RegistryClass = apcore.Registry ?? apcore.default?.Registry; if (!RegistryClass) { throw new Error("Cannot find Registry class in apcore-js"); diff --git a/mcp/typescript/src/cli.ts b/mcp/typescript/src/cli.ts index de66f577..a140f3d5 100644 --- a/mcp/typescript/src/cli.ts +++ b/mcp/typescript/src/cli.ts @@ -134,11 +134,10 @@ export async function main(): Promise { if (!extensionsDir && !fromOpenapi) { let hasConfigBusOpenapi = false; try { - const apcore = await import("apcore-js"); - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const Config = (apcore as any).Config; - const config = typeof Config?.getInstance === "function" ? Config.getInstance() : undefined; - hasConfigBusOpenapi = Boolean(config?.get?.("mcp.openapi")); + const { loadMcpConfig } = await import("./config.js"); + const configured = loadMcpConfig().get("mcp.openapi"); + const spec = (configured as { spec?: unknown } | null)?.spec; + hasConfigBusOpenapi = typeof spec === "string" && spec.trim() !== ""; } catch { // apcore-js not installed — treated the same as "no Config Bus value". } @@ -196,7 +195,7 @@ export async function main(): Promise { discover(): Promise; }; try { - const apcore = await import("apcore-js"); + const apcore = await import("apcore-js/full"); Registry = apcore.Registry; } catch { fail( diff --git a/mcp/typescript/src/config.ts b/mcp/typescript/src/config.ts index 468c1f1e..f280c9c9 100644 --- a/mcp/typescript/src/config.ts +++ b/mcp/typescript/src/config.ts @@ -4,7 +4,7 @@ * Registers the "mcp" namespace so users can configure apcore-mcp via * YAML (under the `mcp:` key) or env vars prefixed with APCORE_MCP_. */ -import { Config } from "apcore-js"; +import { Config } from "apcore-js/config"; export const MCP_NAMESPACE = "mcp"; export const MCP_ENV_PREFIX = "APCORE_MCP"; @@ -51,3 +51,9 @@ export function registerMcpNamespace(): void { // Already registered or registerNamespace not available in this apcore-js version } } + +/** Register MCP defaults before loading the project's configuration. */ +export function loadMcpConfig(): Config { + registerMcpNamespace(); + return Config.load(undefined, { validate: false }); +} diff --git a/mcp/typescript/src/converters/anthropic.ts b/mcp/typescript/src/converters/anthropic.ts new file mode 100644 index 00000000..a6c1be83 --- /dev/null +++ b/mcp/typescript/src/converters/anthropic.ts @@ -0,0 +1,28 @@ +import { ModuleIDNormalizer } from "../adapters/id-normalizer.js"; +import { prepareLlmSchema } from "../adapters/schema.js"; +import type { AnthropicToolDef, ModuleDescriptor } from "../types.js"; + +/** Convert one module descriptor into an Anthropic Messages tool. */ +export class AnthropicConverter { + private readonly names = new ModuleIDNormalizer(); + + convertDescriptor(descriptor: ModuleDescriptor): AnthropicToolDef { + const schema = structuredClone(descriptor.inputSchema); + prepareLlmSchema(schema, true); + const tool: AnthropicToolDef = { + name: this.names.normalize(descriptor.moduleId), + description: descriptor.description, + input_schema: schema, + }; + const examples: Record[] = []; + for (const example of descriptor.examples ?? []) { + if (typeof example !== "object" || example === null || !("inputs" in example)) continue; + const { inputs } = example; + if (typeof inputs === "object" && inputs !== null && !Array.isArray(inputs)) { + examples.push(structuredClone(inputs) as Record); + } + } + if (examples.length > 0) tool.input_examples = examples; + return tool; + } +} diff --git a/mcp/typescript/src/converters/index.ts b/mcp/typescript/src/converters/index.ts index 0d0ad81e..41676f0f 100644 --- a/mcp/typescript/src/converters/index.ts +++ b/mcp/typescript/src/converters/index.ts @@ -2,5 +2,6 @@ * Converters - Re-exports for apcore-to-platform tool definition converters. */ +export { AnthropicConverter } from "./anthropic.js"; export { OpenAIConverter } from "./openai.js"; export type { ConvertOptions, ConvertRegistryOptions } from "./openai.js"; diff --git a/mcp/typescript/src/converters/openai.ts b/mcp/typescript/src/converters/openai.ts index c1232bfc..51637d29 100644 --- a/mcp/typescript/src/converters/openai.ts +++ b/mcp/typescript/src/converters/openai.ts @@ -6,10 +6,11 @@ * chat completions API. */ -import { SchemaConverter } from "../adapters/schema.js"; +import { toStrictSchema } from "apcore-js"; +import { prepareLlmSchema, SchemaConverter } from "../adapters/schema.js"; import { AnnotationMapper } from "../adapters/annotations.js"; import { ModuleIDNormalizer } from "../adapters/id-normalizer.js"; -import type { Registry, ModuleDescriptor, OpenAIToolDef, JsonSchema } from "../types.js"; +import type { Registry, ModuleDescriptor, OpenAIToolDef, OpenAIResponsesToolDef, JsonSchema } from "../types.js"; import { isMarkdownAvailable, renderModuleMarkdownSync } from "../markdown.js"; /** Options shared by convertRegistry and convertDescriptor. */ @@ -153,7 +154,7 @@ export class OpenAIConverter { const richDescription = options?.richDescription ?? false; const name = this._idNormalizer.normalize(descriptor.moduleId); - let parameters = this._schemaConverter.convertInputSchema(descriptor); + let parameters = this._schemaConverter.convertInputSchema(descriptor, { strict: false, inlineRefs: false }); // Resolve the LLM-facing description. Markdown rendering takes // precedence over the plain `descriptor.description`; the @@ -203,6 +204,21 @@ export class OpenAIConverter { }; } + /** Convert one module to a Responses API function tool. */ + convertResponsesDescriptor(descriptor: ModuleDescriptor, options?: ConvertOptions): OpenAIResponsesToolDef { + const tool = this.convertDescriptor(descriptor, options); + return { type: "function", ...tool.function, strict: options?.strict ?? true }; + } + + /** Convert a registry to Responses API function tools. */ + convertResponsesRegistry(registry: Registry, options?: ConvertRegistryOptions): OpenAIResponsesToolDef[] { + return this.convertRegistry(registry, options).map(tool => ({ + type: "function", + ...tool.function, + strict: options?.strict ?? true, + })); + } + /** * Convert a schema to OpenAI strict mode. * @@ -219,174 +235,7 @@ export class OpenAIConverter { */ _applyStrictMode(schema: JsonSchema): JsonSchema { const copy = structuredClone(schema); - // [D11-003] Step 1: promote x-llm-description → description recursively - this._applyLlmDescriptions(copy); - // [D11-003] Step 2: strip all x-* extension keys recursively - this._stripExtensions(copy); - // [D11-003] Steps 3 & 4 happen inside _applyStrictRecursive: - // - delete `default` from every sub-schema - // - sort `required` array alphabetically - // [D11-012] Step 5: wrap optional $ref properties in oneOf nullable - return this._applyStrictRecursive(copy); - } - - /** - * Recursively promote `x-llm-description` → `description` when present. - * Mirrors Rust's `apply_strict_mode` step 1. [D11-003] - */ - private _applyLlmDescriptions(schema: JsonSchema): void { - if (typeof schema !== "object" || schema === null) return; - const obj = schema as Record; - if (typeof obj["x-llm-description"] === "string") { - obj["description"] = obj["x-llm-description"]; - } - for (const value of Object.values(obj)) { - if (typeof value === "object" && value !== null) { - if (Array.isArray(value)) { - for (const item of value) { - this._applyLlmDescriptions(item as JsonSchema); - } - } else { - this._applyLlmDescriptions(value as JsonSchema); - } - } - } - } - - /** - * Recursively strip all keys starting with `x-`, and all `default` keys, from - * every schema node. - * - * Mirrors Rust's `apply_strict_mode` step 2 (`openai.rs:527` retains on - * `!k.starts_with("x-") && k != "default"`) and Python's `_strip_extensions` - * with `strip_defaults=True`. [D11-003] - * - * [A-D-OC-4] `default` used to be deleted only from direct entries of a - * `properties` map inside `_applyStrictRecursive`, so a default on `items`, at - * the schema root, or inside a oneOf/anyOf/allOf branch survived into the - * emitted tool while Rust and Python dropped it. - */ - private _stripExtensions(schema: JsonSchema): void { - if (typeof schema !== "object" || schema === null) return; - const obj = schema as Record; - for (const key of Object.keys(obj)) { - if (key.startsWith("x-") || key === "default") { - delete obj[key]; - } else { - const value = obj[key]; - if (typeof value === "object" && value !== null) { - if (Array.isArray(value)) { - for (const item of value) { - this._stripExtensions(item as JsonSchema); - } - } else { - this._stripExtensions(value as JsonSchema); - } - } - } - } - } - - /** - * Recursively apply strict mode transformations to a schema node (in place). - * - * @param schema - Schema node to transform. - * @returns The transformed schema node. - */ - private _applyStrictRecursive(schema: JsonSchema): JsonSchema { - if (typeof schema !== "object" || schema === null) { - return schema; - } - - // Process object types that have properties - if (schema["type"] === "object" && schema["properties"] !== undefined) { - schema["additionalProperties"] = false; - - const properties = schema["properties"] as Record; - const existingRequired = new Set( - (schema["required"] as string[] | undefined) ?? [], - ); - // [D11-005] Sort property names alphabetically to match Python+Rust output. - const allPropertyNames = Object.keys(properties).sort(); - - // Make optional properties nullable and add them to required - for (const propName of allPropertyNames) { - const propSchema = properties[propName]; - - // [A-D-OC-4] `default` is already gone: _stripExtensions removes it from - // every node before this walker runs. - - // If not already required, make it nullable - if (!existingRequired.has(propName)) { - const currentType = propSchema["type"] as - | string - | string[] - | undefined; - if (currentType !== undefined && currentType !== "null") { - if (Array.isArray(currentType)) { - if (!currentType.includes("null")) { - propSchema["type"] = [...currentType, "null"]; - } - } else { - propSchema["type"] = [currentType, "null"]; - } - } else if (currentType === undefined) { - // [D11-012] Optional $ref property (no `type`) — wrap in oneOf nullable - // to match Python+Rust's handling of pure $ref or composition schemas. - properties[propName] = { oneOf: [structuredClone(propSchema), { type: "null" }] } as JsonSchema; - continue; - } - } - - // Recurse into nested properties - properties[propName] = this._applyStrictRecursive(propSchema); - } - - // [D11-003] All properties become required; [D11-005] sort alphabetically - schema["required"] = allPropertyNames; - } - - // Recurse into array items - if (schema["type"] === "array" && schema["items"] !== undefined) { - schema["items"] = this._applyStrictRecursive( - schema["items"] as JsonSchema, - ); - } - - // Recurse into prefixItems (JSON Schema 2020-12 tuple validation) - if (schema["prefixItems"] !== undefined && Array.isArray(schema["prefixItems"])) { - schema["prefixItems"] = (schema["prefixItems"] as JsonSchema[]).map( - (item) => this._applyStrictRecursive(item) - ); - } - - // [A-D-OC-2] Recurse into composition branches. A Pydantic `Optional[Model]` - // becomes `anyOf: [{type:"object", ...}, {type:"null"}]` after $ref inlining, - // so skipping these left the nested object without additionalProperties: - // false and without hardened `required` — which OpenAI strict mode rejects. - // Mirrors openai.rs:622-637 and Python's _convert_to_strict. - for (const keyword of ["oneOf", "anyOf", "allOf"] as const) { - const branches = schema[keyword]; - if (Array.isArray(branches)) { - schema[keyword] = (branches as JsonSchema[]).map((branch) => - this._applyStrictRecursive(branch), - ); - } - } - - // Recurse into $defs / definitions (caller-provided schemas that still - // carry them). `definitions` is the pre-2019-09 spelling and is what - // Python and Rust both walk alongside `$defs`. - for (const defsKey of ["$defs", "definitions"] as const) { - const defs = schema[defsKey]; - if (defs && typeof defs === "object" && !Array.isArray(defs)) { - const map = defs as Record; - for (const [k, v] of Object.entries(map)) { - map[k] = this._applyStrictRecursive(v); - } - } - } - - return schema; + prepareLlmSchema(copy); + return toStrictSchema(copy); } } diff --git a/mcp/typescript/src/index.ts b/mcp/typescript/src/index.ts index 1d00b036..93dd9a9e 100644 --- a/mcp/typescript/src/index.ts +++ b/mcp/typescript/src/index.ts @@ -15,7 +15,8 @@ import { ExecutionRouter } from "./server/router.js"; import { RegistryListener } from "./server/listener.js"; import { TransportManager } from "./server/transport.js"; import { withStdioOutput, type StdioOutputLease } from "./server/stdio-output.js"; -import { registerMcpNamespace } from "./config.js"; +import { loadMcpConfig } from "./config.js"; +import type { Config } from "apcore-js/config"; import { registerMcpFormatter } from "./adapters/mcp-error-formatter.js"; import type { MetricsExporter } from "./server/transport.js"; import { installObservability, type ObservabilityFlag } from "./server/observability.js"; @@ -38,7 +39,14 @@ import pkg from "../package.json" with { type: "json" }; export const VERSION: string = pkg.version; // ─── Type Exports ──────────────────────────────────────────────────────────── -export type { Registry, Executor, RegistryOrExecutor, OpenAIToolDef } from "./types.js"; +export type { + AnthropicToolDef, + Executor, + OpenAIResponsesToolDef, + OpenAIToolDef, + Registry, + RegistryOrExecutor, +} from "./types.js"; export type { ModuleDescriptor, ModuleAnnotations, @@ -107,7 +115,7 @@ export { ApprovalBridge, APPROVAL_META_TOOL_NAMES } from "./server/approval-brid export type { ApprovalMetaToolName } from "./server/approval-bridge.js"; export { McpErrorFormatter, registerMcpFormatter } from "./adapters/mcp-error-formatter.js"; export { registerMcpNamespace, MCP_NAMESPACE, MCP_ENV_PREFIX, MCP_DEFAULTS } from "./config.js"; -export { OpenAIConverter } from "./converters/openai.js"; +export { AnthropicConverter, OpenAIConverter } from "./converters/index.js"; export type { ConvertOptions, ConvertRegistryOptions } from "./converters/openai.js"; export type { BuildToolsOptions } from "./server/factory.js"; @@ -153,6 +161,7 @@ export async function resolveExecutor( options?: { approvalHandler?: unknown; strategy?: string; + pipelineConfig?: Config; middleware?: unknown[]; acl?: unknown; }, @@ -166,6 +175,9 @@ export async function resolveExecutor( `strategy='${options.strategy}' ignored: input is already an Executor instance.`, ); } + if (options?.pipelineConfig) { + console.warn("mcp.pipeline ignored: input is already an Executor instance."); + } executor = registryOrExecutor as Executor; } else { // It's a bare Registry — create a default Executor @@ -183,10 +195,14 @@ export async function resolveExecutor( if (options?.strategy) { executorOpts.strategy = options.strategy; } + if (options?.pipelineConfig) { + executorOpts.config = options.pipelineConfig; + } executor = new ExecutorClass(executorOpts) as Executor; } - } catch { - // apcore-js not installed — fall through to error + } catch (error) { + if (options?.pipelineConfig) throw error; + // apcore-js not installed — fall through to error. } if (!executor) { throw new Error( @@ -466,86 +482,79 @@ async function loadConfigBusOverrides( callerAcl: unknown | undefined, ): Promise<{ resolvedStrategy: string | undefined; + pipelineConfig?: Config; combinedMiddleware: unknown[]; effectiveAcl: unknown | null; configOpenapi: unknown | null; + projectRoot?: string; configBusDefaults: ConfigBusDefaults; }> { let resolvedStrategy = strategy; let configMiddleware: unknown[] = []; let configAcl: unknown | null = null; - let configOpenapi: unknown | null = null; const configBusDefaults: ConfigBusDefaults = {}; - try { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const apcoreConfig = await import("apcore-js") as any; - const Config = apcoreConfig.Config ?? apcoreConfig.default?.Config; - const buildStrategyFromConfig = apcoreConfig.buildStrategyFromConfig ?? apcoreConfig.default?.buildStrategyFromConfig; - if (Config && buildStrategyFromConfig) { - const config = typeof Config.getInstance === 'function' ? Config.getInstance() : new Config(); - const pipelineCfg = config.get?.("mcp.pipeline"); - if (pipelineCfg && typeof pipelineCfg === 'object' && Object.keys(pipelineCfg).length > 0) { - if (resolvedStrategy) { - console.warn( - `YAML pipeline config found in Config Bus — overriding strategy='${resolvedStrategy}' with config-driven strategy.`, - ); - } - resolvedStrategy = buildStrategyFromConfig(pipelineCfg); - } - // Load declarative middleware from Config Bus (`mcp.middleware`). - const mwCfg = config.get?.("mcp.middleware"); - if (Array.isArray(mwCfg) && mwCfg.length > 0) { - const { buildMiddlewareFromConfig } = await import( - "./middleware-builder.js" - ); - configMiddleware = await buildMiddlewareFromConfig(mwCfg); - } - // Load declarative ACL from Config Bus (`mcp.acl`). - const aclCfg = config.get?.("mcp.acl"); - if (aclCfg) { - const { buildAclFromConfig } = await import("./acl-builder.js"); - configAcl = await buildAclFromConfig(aclCfg); - } - // Read (not build — the registry doesn't exist yet at this point in - // serve()/asyncServe()) the `mcp.openapi` section. PRD F-054 - // Acceptance Criterion 1: `mcp.openapi.spec` alone must start a server. - configOpenapi = config.get?.("mcp.openapi") ?? null; - // [D9-002] Load 9 scalar mcp.* keys. Snake-case → camelCase. - const readStr = (k: string): string | undefined => { - const v = config.get?.(k); - return typeof v === "string" ? v : undefined; - }; - const readNum = (k: string): number | undefined => { - const v = config.get?.(k); - if (typeof v === "number") return v; - if (typeof v === "string" && v !== "") { - const n = Number(v); - if (!Number.isNaN(n)) return n; - } - return undefined; - }; - const readBool = (k: string): boolean | undefined => { - const v = config.get?.(k); - if (typeof v === "boolean") return v; - if (typeof v === "string") { - if (v === "true") return true; - if (v === "false") return false; - } - return undefined; - }; - configBusDefaults.transport = readStr("mcp.transport"); - configBusDefaults.host = readStr("mcp.host"); - configBusDefaults.port = readNum("mcp.port"); - configBusDefaults.name = readStr("mcp.name"); - configBusDefaults.logLevel = readStr("mcp.log_level"); - configBusDefaults.validateInputs = readBool("mcp.validate_inputs"); - configBusDefaults.explorer = readBool("mcp.explorer"); - configBusDefaults.explorerPrefix = readStr("mcp.explorer_prefix"); - configBusDefaults.requireAuth = readBool("mcp.require_auth"); + const config = loadMcpConfig(); + const pipeline = config.get("mcp.pipeline"); + let pipelineConfig: Config | undefined; + if (pipeline && typeof pipeline === "object" && Object.keys(pipeline).length > 0) { + if (resolvedStrategy) { + console.warn("mcp.pipeline takes precedence over the supplied strategy name."); } - } catch { - // apcore-js not installed or Config Bus not available — use strategy param as-is + // Let Core assemble the configured steps with the new Executor's own providers. + config.set("pipeline", pipeline); + pipelineConfig = config; + resolvedStrategy = undefined; + } + // Load declarative middleware from Config Bus (`mcp.middleware`). + const mwCfg = config.get("mcp.middleware"); + if (Array.isArray(mwCfg) && mwCfg.length > 0) { + const { buildMiddlewareFromConfig } = await import( + "./middleware-builder.js" + ); + configMiddleware = await buildMiddlewareFromConfig(mwCfg); } + // Load declarative ACL from Config Bus (`mcp.acl`). + const aclCfg = config.get("mcp.acl"); + if (aclCfg) { + const { buildAclFromConfig } = await import("./acl-builder.js"); + configAcl = await buildAclFromConfig(aclCfg); + } + // Read (not build — the registry doesn't exist yet at this point in + // serve()/asyncServe()) the `mcp.openapi` section. PRD F-054 + // Acceptance Criterion 1: `mcp.openapi.spec` alone must start a server. + const configOpenapi = config.get("mcp.openapi") ?? null; + // [D9-002] Load 9 scalar mcp.* keys. Snake-case → camelCase. + const readStr = (k: string): string | undefined => { + const v = config.get(k); + return typeof v === "string" ? v : undefined; + }; + const readNum = (k: string): number | undefined => { + const v = config.get(k); + if (typeof v === "number") return v; + if (typeof v === "string" && v !== "") { + const n = Number(v); + if (!Number.isNaN(n)) return n; + } + return undefined; + }; + const readBool = (k: string): boolean | undefined => { + const v = config.get(k); + if (typeof v === "boolean") return v; + if (typeof v === "string") { + if (v === "true") return true; + if (v === "false") return false; + } + return undefined; + }; + configBusDefaults.transport = readStr("mcp.transport"); + configBusDefaults.host = readStr("mcp.host"); + configBusDefaults.port = readNum("mcp.port"); + configBusDefaults.name = readStr("mcp.name"); + configBusDefaults.logLevel = readStr("mcp.log_level"); + configBusDefaults.validateInputs = readBool("mcp.validate_inputs"); + configBusDefaults.explorer = readBool("mcp.explorer"); + configBusDefaults.explorerPrefix = readStr("mcp.explorer_prefix"); + configBusDefaults.requireAuth = readBool("mcp.require_auth"); const combinedMiddleware: unknown[] = [...configMiddleware]; if (callerMiddleware && callerMiddleware.length > 0) { @@ -555,7 +564,7 @@ async function loadConfigBusOverrides( // Caller-supplied ACL wins over Config Bus. const effectiveAcl = callerAcl !== undefined ? callerAcl : configAcl; - return { resolvedStrategy, combinedMiddleware, effectiveAcl, configOpenapi, configBusDefaults }; + return { resolvedStrategy, pipelineConfig, combinedMiddleware, effectiveAcl, configOpenapi, projectRoot: config.projectRoot, configBusDefaults }; } /** @@ -805,7 +814,7 @@ async function serveInternal( const origError = console.error; // ── F-040: YAML Pipeline Config via Config Bus ───────────────────── - const { resolvedStrategy, combinedMiddleware, effectiveAcl, configOpenapi, configBusDefaults } = + const { resolvedStrategy, pipelineConfig, combinedMiddleware, effectiveAcl, configOpenapi, projectRoot, configBusDefaults } = await loadConfigBusOverrides(strategy, callerMiddleware, callerAcl); const transport = optTransport ?? configBusDefaults.transport ?? "stdio"; @@ -826,7 +835,7 @@ async function serveInternal( ); } const { buildOpenapiBackendFromConfig } = await import("./openapi-backend.js"); - resolvedBackend = (await buildOpenapiBackendFromConfig(configOpenapi)) as unknown as RegistryOrExecutor; + resolvedBackend = (await buildOpenapiBackendFromConfig(configOpenapi, { projectRoot })) as unknown as RegistryOrExecutor; } else { resolvedBackend = registryOrExecutor; if (configOpenapi) { @@ -875,6 +884,7 @@ async function serveInternal( const executor = await resolveExecutor(resolvedBackend, { approvalHandler: scopedApproval?.handler ?? effectiveApprovalHandler, strategy: resolvedStrategy, + pipelineConfig, middleware: combinedMiddleware, acl: effectiveAcl, }); @@ -920,8 +930,6 @@ async function serveInternal( ); const resolvedMetricsCollector = obsStack.metricsCollector; - // Register MCP config namespace and error formatter (idempotent) - registerMcpNamespace(); await registerMcpFormatter(); // Build output schema map for redaction @@ -1160,7 +1168,7 @@ export async function asyncServe( const origError = console.error; // ── F-040: YAML Pipeline Config via Config Bus ───────────────────── - const { resolvedStrategy, combinedMiddleware, effectiveAcl, configOpenapi, configBusDefaults } = + const { resolvedStrategy, pipelineConfig, combinedMiddleware, effectiveAcl, configOpenapi, projectRoot, configBusDefaults } = await loadConfigBusOverrides(strategy, callerMiddleware, callerAcl); // PRD F-054 Acceptance Criterion 1: `mcp.openapi.spec` alone, with no @@ -1178,7 +1186,7 @@ export async function asyncServe( ); } const { buildOpenapiBackendFromConfig } = await import("./openapi-backend.js"); - resolvedBackend = (await buildOpenapiBackendFromConfig(configOpenapi)) as unknown as RegistryOrExecutor; + resolvedBackend = (await buildOpenapiBackendFromConfig(configOpenapi, { projectRoot })) as unknown as RegistryOrExecutor; } else { resolvedBackend = registryOrExecutor; if (configOpenapi) { @@ -1214,6 +1222,7 @@ export async function asyncServe( const executor = await resolveExecutor(resolvedBackend, { approvalHandler: scopedApproval?.handler ?? effectiveApprovalHandler, strategy: resolvedStrategy, + pipelineConfig, middleware: combinedMiddleware, acl: effectiveAcl, }); @@ -1265,7 +1274,6 @@ export async function asyncServe( const resolvedMetricsCollector = obsStack.metricsCollector; // Register MCP config namespace and error formatter (idempotent) - registerMcpNamespace(); await registerMcpFormatter(); // Build output schema map for redaction diff --git a/mcp/typescript/src/middleware-builder.ts b/mcp/typescript/src/middleware-builder.ts index d2260273..e2047d21 100644 --- a/mcp/typescript/src/middleware-builder.ts +++ b/mcp/typescript/src/middleware-builder.ts @@ -56,7 +56,7 @@ export async function buildMiddlewareFromConfig( let apcore: Record; try { // eslint-disable-next-line @typescript-eslint/no-explicit-any - apcore = (await import("apcore-js")) as any; + apcore = (await import("apcore-js/full")) as any; } catch (err) { throw new Error( `Config Bus 'mcp.middleware' requires apcore-js>=0.18 with middleware support: ${ diff --git a/mcp/typescript/src/openapi-backend.ts b/mcp/typescript/src/openapi-backend.ts index c8c3b7f9..44a95bb8 100644 --- a/mcp/typescript/src/openapi-backend.ts +++ b/mcp/typescript/src/openapi-backend.ts @@ -14,6 +14,7 @@ import path from "node:path"; import { Registry } from "apcore-js"; +import { loadMcpConfig } from "./config.js"; import { HTTPProxyRegistryWriter, OpenAPIScanner, @@ -374,13 +375,7 @@ function warnIfWritesHaveNoApprovalPath( */ async function configProjectRoot(): Promise { try { - const apcore = (await import("apcore-js")) as Record; - const Config = apcore.Config ?? apcore.default?.Config; - if (!Config) return undefined; - const config = - typeof Config.getInstance === "function" ? Config.getInstance() : new Config(); - const root = config?.projectRoot; - return typeof root === "string" && root !== "" ? root : undefined; + return loadMcpConfig().projectRoot; } catch { return undefined; } diff --git a/mcp/typescript/src/server/async-task-bridge.ts b/mcp/typescript/src/server/async-task-bridge.ts index b247f950..3fed7be0 100644 --- a/mcp/typescript/src/server/async-task-bridge.ts +++ b/mcp/typescript/src/server/async-task-bridge.ts @@ -778,7 +778,7 @@ export async function createAsyncTaskBridge( if (options?.enabled === false) return null; try { // eslint-disable-next-line @typescript-eslint/no-explicit-any - const apcore = (await import("apcore-js")) as any; + const apcore = (await import("apcore-js/full")) as any; const AsyncTaskManager = apcore.AsyncTaskManager ?? apcore.default?.AsyncTaskManager; if (!AsyncTaskManager) return null; const manager = new AsyncTaskManager({ diff --git a/mcp/typescript/src/server/observability.ts b/mcp/typescript/src/server/observability.ts index 60ebbd0e..095720e1 100644 --- a/mcp/typescript/src/server/observability.ts +++ b/mcp/typescript/src/server/observability.ts @@ -89,7 +89,7 @@ export async function installObservability( let apcoreMod: Record; try { // eslint-disable-next-line @typescript-eslint/no-explicit-any - apcoreMod = (await import("apcore-js")) as any; + apcoreMod = (await import("apcore-js/observability")) as any; } catch { console.warn( "[apcore-mcp] observability requested but apcore-js is not installed; skipping auto-wire.", diff --git a/mcp/typescript/src/types.ts b/mcp/typescript/src/types.ts index 51d5b193..214e5beb 100644 --- a/mcp/typescript/src/types.ts +++ b/mcp/typescript/src/types.ts @@ -194,6 +194,21 @@ export interface OpenAIToolDef { }; } +export interface OpenAIResponsesToolDef { + type: "function"; + name: string; + description: string; + parameters: JsonSchema; + strict: boolean; +} + +export interface AnthropicToolDef { + name: string; + description: string; + input_schema: JsonSchema; + input_examples?: Record[]; +} + // ─── Utility Types ─────────────────────────────────────────────────────────── export interface TextContentDict { diff --git a/mcp/typescript/tests/acl-approval-gating-e2e.test.ts b/mcp/typescript/tests/acl-approval-gating-e2e.test.ts index aa864b9a..1da60282 100644 --- a/mcp/typescript/tests/acl-approval-gating-e2e.test.ts +++ b/mcp/typescript/tests/acl-approval-gating-e2e.test.ts @@ -1,3 +1,5 @@ +import { Config } from 'apcore-js/config'; +import { registerSysModules } from 'apcore-js/sys-modules'; /** * End-to-end: an ACL-sourced approval requirement gates a real MCP tools/call. * @@ -99,6 +101,8 @@ async function buildRouter(): Promise<{ const handler = new RecordingApprovalHandler(); const executor = new apcore.Executor({ + // Isolate the caller-specific ACL requirement from destructive defaults. + policy: new apcore.ExecutionPolicy([], { gateDestructive: false }), registry, acl, approvalHandler: handler as never, @@ -178,10 +182,10 @@ describe("ACL enforcement on apcore:// management resource reads", () => { const executor = new apcore.Executor({ registry }) as { setAcl?: (acl: unknown) => void; }; - const config = new apcore.Config({ + const config = new Config({ sys_modules: { enabled: true, events: { enabled: true } }, }); - apcore.registerSysModules(registry, executor, config, null); + registerSysModules(registry, executor, config, null); executor.setAcl?.(new apcore.ACL([{ callers: ["*"], targets: ["system.*"], effect }], "deny")); const factory = new MCPServerFactory(); diff --git a/mcp/typescript/tests/acl-rule-template.test.ts b/mcp/typescript/tests/acl-rule-template.test.ts index 7eb83054..40eb3875 100644 --- a/mcp/typescript/tests/acl-rule-template.test.ts +++ b/mcp/typescript/tests/acl-rule-template.test.ts @@ -1,3 +1,5 @@ +import { Config } from "apcore-js/config"; +import { registerSysModules } from "apcore-js/sys-modules"; /** * Tests for the ACL rule template shipped in `src/acl-builder.ts`'s doc * comment (aiperceivable/apcore-mcp#14) and the `approval` rule field @@ -45,10 +47,10 @@ describe("ACL rule template targets match registered system.* module ids", () => // modules register too (registration.ts gates them behind the events // branch) — otherwise only the six read modules would exist and the // "system.control.*" pattern would match nothing, silently. - const config = new apcore.Config({ + const config = new Config({ sys_modules: { enabled: true, events: { enabled: true } }, }); - apcore.registerSysModules(registry, executor, config, null); + registerSysModules(registry, executor, config, null); const registeredIds: string[] = registry.list({ visibility: ["public", "hidden"] }); expect(registeredIds.length).toBeGreaterThan(0); diff --git a/mcp/typescript/tests/cli.test.ts b/mcp/typescript/tests/cli.test.ts index c9ad95d0..7511124d 100644 --- a/mcp/typescript/tests/cli.test.ts +++ b/mcp/typescript/tests/cli.test.ts @@ -99,33 +99,28 @@ describe("CLI (cli.ts)", () => { process.argv = ["node", "cli.js", ...args]; - // Always mock apcore-js to prevent Vite resolution errors if (useRealApcoreJs) { - // openapi-backend.ts's internals (registry.register/list via the real - // toolkit writer) need a functional Registry, not the {discover} stub - // below — used only by the tests that actually exercise --from-openapi - // end to end. - vi.doMock("apcore-js", async () => vi.importActual("apcore-js")); + // --from-openapi needs a functional Registry for the Toolkit writer. + vi.doMock("apcore-js/full", async () => vi.importActual("apcore-js/full")); } else if (apcoreAvailable) { - vi.doMock("apcore-js", async (importOriginal) => ({ - ...await importOriginal(), + vi.doMock("apcore-js/full", async (importOriginal) => ({ + ...await importOriginal(), Registry: vi.fn(function () { return { discover: vi.fn().mockResolvedValue(discoverCount), }; }), - // Only present when a test needs to exercise the mcp.openapi - // Config-Bus fallback (A-001) — real apcore-js's Config.getInstance() - // shape, narrowed to just what cli.ts reads. - Config: configOpenapi === undefined ? undefined : { - getInstance: () => ({ - get: (key: string) => (key === "mcp.openapi" ? configOpenapi : undefined), - }), - }, })); } else { - vi.doMock("apcore-js", () => { - throw new Error("Cannot find module 'apcore-js'"); + vi.doMock("apcore-js/full", () => { + throw new Error("Cannot find module 'apcore-js/full'"); }); } + vi.doMock("apcore-js/config", () => ({ + Config: configOpenapi === undefined ? undefined : { + load: () => ({ + get: (key: string) => (key === "mcp.openapi" ? configOpenapi : undefined), + }), + }, + })); // Always mock index.js for serve/VERSION/JWTAuthenticator/ElicitationApprovalHandler const mockServe = serveFn ?? vi.fn().mockResolvedValue(undefined); diff --git a/mcp/typescript/tests/config-bus.test.ts b/mcp/typescript/tests/config-bus.test.ts index fa5b1c82..ac06495e 100644 --- a/mcp/typescript/tests/config-bus.test.ts +++ b/mcp/typescript/tests/config-bus.test.ts @@ -1,11 +1,14 @@ /** * D9-002: Config Bus deduplication — regression test. * - * Verifies that both serve() and asyncServe() call Config.getInstance() + * Verifies that both serve() and asyncServe() call Config.load() * exactly once each (via loadConfigBusOverrides), not twice. */ -import { describe, it, expect, vi, beforeEach } from "vitest"; +import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { describe, it, expect, vi, afterEach, beforeEach } from "vitest"; import type { Executor, Registry } from "../src/types.js"; // --------------------------------------------------------------------------- @@ -42,21 +45,18 @@ vi.mock("../src/server/factory.js", () => ({ }; }), })); -const getInstanceSpy = vi.fn().mockReturnValue({ get: vi.fn().mockReturnValue(null) }); +const loadConfigSpy = vi.fn().mockReturnValue({ get: vi.fn().mockReturnValue(null) }); -vi.mock("apcore-js", async (importOriginal) => ({ - ...await importOriginal(), - Config: { - getInstance: (...args: unknown[]) => getInstanceSpy(...args), - }, - buildStrategyFromConfig: vi.fn(), - default: { +vi.mock("apcore-js/config", async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, Config: { - getInstance: (...args: unknown[]) => getInstanceSpy(...args), + registerNamespace: actual.Config.registerNamespace.bind(actual.Config), + load: (...args: unknown[]) => loadConfigSpy(...args), }, - buildStrategyFromConfig: vi.fn(), - }, -})); + }; +}); import { serve, asyncServe } from "../src/index.js"; @@ -85,23 +85,23 @@ function makeExecutor(registry: Registry): Executor { describe("D9-002: Config Bus deduplication", () => { beforeEach(() => { - getInstanceSpy.mockClear(); - getInstanceSpy.mockReturnValue({ get: vi.fn().mockReturnValue(null) }); + loadConfigSpy.mockClear(); + loadConfigSpy.mockReturnValue({ get: vi.fn().mockReturnValue(null) }); }); - it("serve() calls Config.getInstance() exactly once via loadConfigBusOverrides", async () => { + it("serve() calls Config.load() exactly once via loadConfigBusOverrides", async () => { const registry = makeRegistry(); const executor = makeExecutor(registry); await serve(executor, { transport: "stdio" }); - expect(getInstanceSpy).toHaveBeenCalledTimes(1); + expect(loadConfigSpy).toHaveBeenCalledTimes(1); }); - it("asyncServe() calls Config.getInstance() exactly once via loadConfigBusOverrides", async () => { + it("asyncServe() calls Config.load() exactly once via loadConfigBusOverrides", async () => { const registry = makeRegistry(); const executor = makeExecutor(registry); const app = await asyncServe(executor, {}); await app.close(); - expect(getInstanceSpy).toHaveBeenCalledTimes(1); + expect(loadConfigSpy).toHaveBeenCalledTimes(1); }); }); @@ -110,13 +110,13 @@ describe("D9-002: Config Bus scalar key reads (transport/host/port)", () => { // Reset transport mock state per test. const { TransportManager } = await import("../src/server/transport.js"); (TransportManager as unknown as { mockClear: () => void }).mockClear(); - getInstanceSpy.mockClear(); + loadConfigSpy.mockClear(); }); it("uses Config Bus mcp.port when caller does not pass port", async () => { // Stub Config.get to return port 9000 for mcp.port (matching the audit's // canonical example: APCORE_MCP_PORT=9000). - getInstanceSpy.mockReturnValue({ + loadConfigSpy.mockReturnValue({ get: vi.fn((k: string) => { if (k === "mcp.port") return 9000; if (k === "mcp.transport") return "streamable-http"; @@ -139,7 +139,7 @@ describe("D9-002: Config Bus scalar key reads (transport/host/port)", () => { }); it("caller-supplied port wins over Config Bus mcp.port", async () => { - getInstanceSpy.mockReturnValue({ + loadConfigSpy.mockReturnValue({ get: vi.fn((k: string) => { if (k === "mcp.port") return 9000; if (k === "mcp.transport") return "streamable-http"; @@ -162,7 +162,7 @@ describe("D9-002: Config Bus scalar key reads (transport/host/port)", () => { describe("stdio reservation while resolving Config Bus transport", () => { it("reserves unspecified bootstrap, then restores before Config-selected HTTP setup", async () => { const stdout = process.stdout.write; - getInstanceSpy.mockImplementationOnce(() => { + loadConfigSpy.mockImplementationOnce(() => { expect(process.stdout.write).not.toBe(stdout); return { get: (key: string) => key === "mcp.transport" ? "streamable-http" : null }; }); @@ -173,3 +173,61 @@ describe("stdio reservation while resolving Config Bus transport", () => { expect(process.stdout.write).toBe(stdout); }); }); + +describe("MCP project YAML through Core Config.load", () => { + afterEach(() => vi.unstubAllEnvs()); + + it("applies transport, port, and name to the actual startup path", async () => { + const directory = mkdtempSync(join(tmpdir(), "apcore-mcp-project-config-")); + try { + const path = join(directory, "apcore.yaml"); + writeFileSync(path, [ + "apcore:", + " version: 1.0.0", + " project: {name: test-project}", + "mcp:", + " transport: streamable-http", + " port: 9042", + " name: yaml-server", + ].join("\n")); + vi.stubEnv("APCORE_CONFIG_FILE", path); + const actual = await vi.importActual("apcore-js/config"); + loadConfigSpy.mockImplementationOnce(() => actual.Config.load(undefined, { validate: false })); + + await serve(makeExecutor(makeRegistry()), { async: false }); + + const { TransportManager } = await import("../src/server/transport.js"); + const instances = vi.mocked(TransportManager).mock.results; + expect(instances.at(-1)?.value.runStreamableHttp).toHaveBeenCalledWith( + expect.anything(), + expect.objectContaining({ port: 9042 }), + ); + const { MCPServerFactory } = await import("../src/server/factory.js"); + expect(vi.mocked(MCPServerFactory).mock.results.at(-1)?.value.createServer) + .toHaveBeenCalledWith("yaml-server", expect.any(String), expect.anything()); + } finally { + rmSync(directory, { recursive: true, force: true }); + } + }); + + it("starts with stdio defaults when no configuration file exists", async () => { + const directory = mkdtempSync(join(tmpdir(), "apcore-mcp-no-config-")); + try { + vi.stubEnv("APCORE_CONFIG_FILE", undefined); + vi.stubEnv("HOME", directory); + vi.stubEnv("XDG_CONFIG_HOME", directory); + const actual = await vi.importActual("apcore-js/config"); + const config = actual.Config.load(undefined, { validate: false }); + expect(config.sourcePath).toBeNull(); + loadConfigSpy.mockReturnValueOnce(config); + + await serve(makeExecutor(makeRegistry()), { async: false }); + + const { TransportManager } = await import("../src/server/transport.js"); + expect(vi.mocked(TransportManager).mock.results.at(-1)?.value.runStdio) + .toHaveBeenCalledOnce(); + } finally { + rmSync(directory, { recursive: true, force: true }); + } + }); +}); diff --git a/mcp/typescript/tests/converters/openai.test.ts b/mcp/typescript/tests/converters/openai.test.ts index c610c9c1..aeefa93f 100644 --- a/mcp/typescript/tests/converters/openai.test.ts +++ b/mcp/typescript/tests/converters/openai.test.ts @@ -1,7 +1,51 @@ +import { readFileSync } from "node:fs"; import { describe, it, expect } from "vitest"; -import { OpenAIConverter } from "../../src/converters/openai.js"; +import { AnthropicConverter, OpenAIConverter } from "../../src/index.js"; +import { MCPServerFactory } from "../../src/server/factory.js"; import type { ModuleDescriptor, Registry } from "../../src/types.js"; +it("matches the shared provider tool projection", () => { + const fixture = JSON.parse(readFileSync( + new URL("../../../conformance/fixtures/tool_projection.json", import.meta.url), "utf8", + )); + const module = fixture.module; + const descriptor: ModuleDescriptor = { + moduleId: module.module_id, + description: module.description, + inputSchema: module.input_schema, + outputSchema: module.output_schema, + annotations: null, + examples: module.examples, + }; + const registry = createMockRegistry({ [descriptor.moduleId]: descriptor }); + const openai = new OpenAIConverter(); + const expected = fixture.expected; + expect(openai.convertRegistry(registry)).toEqual([expected.openai_chat]); + expect(openai.convertResponsesDescriptor(descriptor, { strict: false })).toEqual(expected.openai_responses_non_strict); + expect(openai.convertResponsesRegistry(registry)).toEqual([{ type: "function", ...expected.openai_chat.function }]); + expect(new AnthropicConverter().convertDescriptor(descriptor)).toEqual(expected.anthropic); + + const factory = new MCPServerFactory(); + const annotations = { + readonly: false, destructive: false, idempotent: false, openWorld: true, + requiresApproval: true, streaming: true, + }; + const tool = factory.buildTool({ ...descriptor, annotations }); + expect(tool.name).toBe(descriptor.moduleId); + expect(tool.inputSchema).toEqual(descriptor.inputSchema); + expect(tool.outputSchema).toEqual(descriptor.outputSchema); + expect(tool._meta).toEqual(expected.mcp_meta); + expect(tool.annotations).not.toHaveProperty("requiresApproval"); + expect(tool.annotations).not.toHaveProperty("streaming"); + expect(factory.buildTool(descriptor)._meta).toBeUndefined(); + + const recursive = { ...descriptor, inputSchema: fixture.recursive_input_schema }; + expect(new AnthropicConverter().convertDescriptor(recursive).input_schema).toEqual(recursive.inputSchema); + expect(openai.convertDescriptor(recursive).function.parameters).toHaveProperty( + ["$defs", "node", "properties", "children", "items", "$ref"], "#/$defs/node", + ); +}); + // --------------------------------------------------------------------------- // Helpers // --------------------------------------------------------------------------- @@ -632,7 +676,7 @@ describe("OpenAIConverter", () => { }); // D11-012: Missing oneOf nullable wrap for $ref properties - it("D11-012: wraps optional $ref property in oneOf nullable", () => { + it("wraps an optional $ref property in the A23 anyOf nullable form", () => { // Call _applyStrictMode directly because SchemaConverter inlines $refs // before the converter sees the schema. The raw schema here simulates // what a caller might pass directly to _applyStrictMode. @@ -646,7 +690,7 @@ describe("OpenAIConverter", () => { const result = converter._applyStrictMode(schema) as Record; const props = result.properties as Record; expect(props.id).toEqual({ - oneOf: [{ "$ref": "#/$defs/ID" }, { type: "null" }], + anyOf: [{ "$ref": "#/$defs/ID" }, { type: "null" }], }); }); }); diff --git a/mcp/typescript/tests/fixtures/stdio-cli.ts b/mcp/typescript/tests/fixtures/stdio-cli.ts index 2ae58bfc..485c0779 100644 --- a/mcp/typescript/tests/fixtures/stdio-cli.ts +++ b/mcp/typescript/tests/fixtures/stdio-cli.ts @@ -1,9 +1,11 @@ -import { Config, Registry } from "apcore-js"; +import { Config } from "apcore-js/config"; +import { Registry } from "apcore-js/full"; // Instrument configuration construction without replacing the real SDK Config. -Object.defineProperty(Config, "getInstance", { value: () => { +const load = Config.load; +Config.load = (...args: Parameters) => { console.log("config bootstrap diagnostic"); - return new Config(); -} }); + return load.apply(Config, args); +}; const discover = Registry.prototype.discover; Registry.prototype.discover = function (...args: Parameters) { console.log("discovery bootstrap diagnostic"); diff --git a/mcp/typescript/tests/fixtures/stdio-noise.ts b/mcp/typescript/tests/fixtures/stdio-noise.ts index 9736024a..e7ed2cff 100644 --- a/mcp/typescript/tests/fixtures/stdio-noise.ts +++ b/mcp/typescript/tests/fixtures/stdio-noise.ts @@ -1,5 +1,7 @@ /** Real dependency fixture; run with node --import tsx tests/fixtures/stdio-noise.ts. */ -import { Executor, LoggingMiddleware, Registry, StdoutExporter, StdoutSubscriber, TracingMiddleware } from "apcore-js"; +import { Executor, LoggingMiddleware, Registry } from "apcore-js"; +import { StdoutSubscriber } from "apcore-js/events"; +import { StdoutExporter, TracingMiddleware } from "apcore-js/observability"; import { DisplayResolver } from "apcore-toolkit"; import { serve } from "../../src/index.js"; diff --git a/mcp/typescript/tests/openapi-backend-wiring.test.ts b/mcp/typescript/tests/openapi-backend-wiring.test.ts index 6e6b15bd..319db496 100644 --- a/mcp/typescript/tests/openapi-backend-wiring.test.ts +++ b/mcp/typescript/tests/openapi-backend-wiring.test.ts @@ -25,9 +25,9 @@ import type { AddressInfo } from "node:net"; const state = vi.hoisted(() => ({ projectRoot: undefined as string | undefined })); -vi.mock("apcore-js", async (importOriginal) => { +vi.mock("apcore-js/config", async (importOriginal) => { const actual = await importOriginal>(); - const Config = { getInstance: () => ({ projectRoot: state.projectRoot }) }; + const Config = { load: () => ({ projectRoot: state.projectRoot }) }; return { ...actual, Config, diff --git a/mcp/typescript/tests/server/scoped-approval.test.ts b/mcp/typescript/tests/server/scoped-approval.test.ts index d00f47df..45ada979 100644 --- a/mcp/typescript/tests/server/scoped-approval.test.ts +++ b/mcp/typescript/tests/server/scoped-approval.test.ts @@ -6,6 +6,8 @@ import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/ import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js"; import type { CallToolResult } from "@modelcontextprotocol/sdk/types.js"; import * as core from "apcore-js"; +import { EventEmitter } from "apcore-js/events"; +import { AsyncTaskManager } from "apcore-js/full"; import { describe, expect, it, vi } from "vitest"; import { StorageBackedApprovalHandler, supportsScopedCore } from "../../src/adapters/approval.js"; import { InMemoryApprovalStore } from "../../src/approval-store.js"; @@ -42,7 +44,7 @@ async function connect(options: { streaming?: boolean; background?: boolean; tra const store = new InMemoryApprovalStore(); const notify = vi.fn().mockResolvedValue(undefined); const handler = new StorageBackedApprovalHandler(store, { notifyCallback: notify }).forMcpServer(); - const events = new core.EventEmitter(); + const events = new EventEmitter(); const audit: Record[] = []; events.subscribe({ eventPattern: "apcore.approval.decision", @@ -71,7 +73,7 @@ async function connect(options: { streaming?: boolean; background?: boolean; tra execute: () => ({ job: "ordinary" }), } as never); const executor = new core.Executor({ registry, approvalHandler: handler as never, eventEmitter: events }); - const manager = options.background ? new core.AsyncTaskManager({ executor }) : undefined; + const manager = options.background ? new AsyncTaskManager({ executor }) : undefined; const asyncTaskBridge = manager ? new AsyncTaskBridge(manager as never, { descriptorLookup: id => registry.getDefinition(id) as never, }) : undefined; diff --git a/mcp/typescript/tests/server/stream-completion.test.ts b/mcp/typescript/tests/server/stream-completion.test.ts index 1c125f7d..98ebe44d 100644 --- a/mcp/typescript/tests/server/stream-completion.test.ts +++ b/mcp/typescript/tests/server/stream-completion.test.ts @@ -1,6 +1,7 @@ import { Client } from "@modelcontextprotocol/sdk/client/index.js"; import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js"; import * as core from "apcore-js"; +import { Config } from "apcore-js/config"; import { cp, mkdir, mkdtemp, realpath, rm, symlink } from "node:fs/promises"; import { tmpdir } from "node:os"; import { dirname, join } from "node:path"; @@ -19,6 +20,7 @@ async function connect( declaresStreaming = true, sdk = core, throughFacade = false, + ConfigClass = Config, ) { let calls = 0; let streams = 0; @@ -41,7 +43,7 @@ async function connect( yield { group: { detail: { right: true } }, items: [2] }; }, } as never); - const config = new sdk.Config({ stream: { max_merge_depth: 1 } }); + const config = new ConfigClass({ stream: { max_merge_depth: 1 } }); const executor = throughFacade ? new sdk.APCore({ registry, config }) : new sdk.Executor({ registry, config }); if (fail === "after") executor.useAfter(() => { throw new Error("private-after-cause"); }); const target = await connectClient(registry, executor, outputSchema); @@ -118,7 +120,10 @@ it.each([false, true])("uses an independent Core package (facade: %s)", async (t expect(sdk.Executor).not.toBe(core.Executor); expect(sdk.APCore).not.toBe(core.APCore); const notifications: unknown[] = []; - const target = await connect(hasCompletion ? null : "after", false, sdk, throughFacade); + const { Config: CopyConfig }: { Config: typeof Config } = await import( + /* @vite-ignore */ pathToFileURL(join(packageRoot, "dist", "config-entry.js")).href + ); + const target = await connect(hasCompletion ? null : "after", false, sdk, throughFacade, CopyConfig); try { const result = await target.client.callTool({ name: moduleId, arguments: {} }, undefined, hasCompletion ? undefined : { onprogress: ({ message }) => { notifications.push(message); }, diff --git a/mcp/typescript/tests/system-surface-conformance.test.ts b/mcp/typescript/tests/system-surface-conformance.test.ts index 109e375e..b547013d 100644 --- a/mcp/typescript/tests/system-surface-conformance.test.ts +++ b/mcp/typescript/tests/system-surface-conformance.test.ts @@ -1,3 +1,5 @@ +import { Config } from "apcore-js/config"; +import { registerSysModules } from "apcore-js/sys-modules"; /** * Cross-language conformance: the nine canonical system.* modules -> exact MCP primitive. * @@ -49,8 +51,8 @@ async function realRegistryAndExecutor(): Promise<{ registry: unknown; executor: const apcore = (await import("apcore-js")) as unknown as ApcoreJsModule; const registry = new apcore.Registry(); const executor = new apcore.Executor({ registry }); - const config = new apcore.Config(FIXTURE!.setup.config); - apcore.registerSysModules(registry, executor, config, null); + const config = new Config(FIXTURE!.setup.config); + registerSysModules(registry, executor, config, null); return { registry, executor }; } diff --git a/mcp/typescript/vitest.config.ts b/mcp/typescript/vitest.config.ts index 5e65108c..df3a6a6a 100644 --- a/mcp/typescript/vitest.config.ts +++ b/mcp/typescript/vitest.config.ts @@ -4,6 +4,8 @@ export default defineConfig({ test: { globals: true, environment: "node", + // Keep installed SDK subpaths inside Vitest's loader for boundary mocks. + server: { deps: { inline: ["apcore-js"] } }, include: ["tests/**/*.test.ts"], coverage: { provider: "v8", diff --git a/toolkit/python/pyproject.toml b/toolkit/python/pyproject.toml index ca84514d..4b981f78 100644 --- a/toolkit/python/pyproject.toml +++ b/toolkit/python/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "hatchling.build" [project] name = "apcore-toolkit" -version = "0.15.1a1" +version = "0.15.1a2" description = "Shared scanner, schema extraction, and output toolkit for apcore framework adapters" requires-python = ">=3.11" readme = "README.md" @@ -23,7 +23,7 @@ keywords = [ "toolkit", ] dependencies = [ - "apcore>=0.33.0,<=1.0.0a1", + "apcore>=0.33.0,<=1.0.0a2", "pydantic>=2.0", "PyYAML>=6.0", ] diff --git a/toolkit/python/src/apcore_toolkit/ai_enhancer.py b/toolkit/python/src/apcore_toolkit/ai_enhancer.py index d32f6e4e..cd1d677f 100644 --- a/toolkit/python/src/apcore_toolkit/ai_enhancer.py +++ b/toolkit/python/src/apcore_toolkit/ai_enhancer.py @@ -19,7 +19,7 @@ from dataclasses import replace from typing import Any, Callable, Protocol -from apcore import DEFAULT_ANNOTATIONS, ModuleAnnotations +from apcore.module import DEFAULT_ANNOTATIONS, ModuleAnnotations from apcore_toolkit.types import ScannedModule diff --git a/toolkit/python/src/apcore_toolkit/binding_loader.py b/toolkit/python/src/apcore_toolkit/binding_loader.py index 14c46e2f..be867970 100644 --- a/toolkit/python/src/apcore_toolkit/binding_loader.py +++ b/toolkit/python/src/apcore_toolkit/binding_loader.py @@ -17,7 +17,7 @@ from pathlib import Path from typing import Any -from apcore import ModuleAnnotations, ModuleExample +from apcore.module import ModuleAnnotations, ModuleExample from apcore_toolkit.types import ScannedModule diff --git a/toolkit/python/src/apcore_toolkit/formatting/surface.py b/toolkit/python/src/apcore_toolkit/formatting/surface.py index c240f7b1..dd361f9f 100644 --- a/toolkit/python/src/apcore_toolkit/formatting/surface.py +++ b/toolkit/python/src/apcore_toolkit/formatting/surface.py @@ -11,7 +11,7 @@ import json from typing import Any, Literal -from apcore import ModuleAnnotations +from apcore.module import ModuleAnnotations from apcore_toolkit.serializers import annotations_to_dict, module_to_dict from apcore_toolkit.types import ScannedModule diff --git a/toolkit/python/src/apcore_toolkit/output/http_proxy_writer.py b/toolkit/python/src/apcore_toolkit/output/http_proxy_writer.py index 8e104db7..c21950ed 100644 --- a/toolkit/python/src/apcore_toolkit/output/http_proxy_writer.py +++ b/toolkit/python/src/apcore_toolkit/output/http_proxy_writer.py @@ -32,8 +32,9 @@ from typing import Any from urllib.parse import quote, urlparse -from apcore import DEFAULT_ANNOTATIONS, ErrorCodes, Registry -from apcore.errors import ModuleError +from apcore.errors import ErrorCodes, ModuleError +from apcore.module import DEFAULT_ANNOTATIONS +from apcore.registry import Registry from apcore_toolkit.http_verb_map import ( _effective_openapi_path, _openapi_path_param_names, diff --git a/toolkit/python/src/apcore_toolkit/output/registry_writer.py b/toolkit/python/src/apcore_toolkit/output/registry_writer.py index cd80e003..d82f7ea5 100644 --- a/toolkit/python/src/apcore_toolkit/output/registry_writer.py +++ b/toolkit/python/src/apcore_toolkit/output/registry_writer.py @@ -19,7 +19,8 @@ from apcore_toolkit.serializers import annotations_to_dict if TYPE_CHECKING: - from apcore import FunctionModule, Registry + from apcore.decorator import FunctionModule + from apcore.registry import Registry from apcore_toolkit.types import ScannedModule @@ -252,7 +253,7 @@ def _build_function_module( annotations: Override for the annotations dict; when ``_UNSET`` it is derived from ``mod.annotations``. Used to clear ``streaming``. """ - from apcore import FunctionModule + from apcore.decorator import FunctionModule ann = annotations_to_dict(mod.annotations) if annotations is _UNSET else annotations return FunctionModule( diff --git a/toolkit/python/src/apcore_toolkit/scanner.py b/toolkit/python/src/apcore_toolkit/scanner.py index 95472cd7..2e7a7b00 100644 --- a/toolkit/python/src/apcore_toolkit/scanner.py +++ b/toolkit/python/src/apcore_toolkit/scanner.py @@ -12,7 +12,7 @@ from dataclasses import replace from typing import Any -from apcore import DEFAULT_ANNOTATIONS, ModuleAnnotations +from apcore.module import DEFAULT_ANNOTATIONS, ModuleAnnotations from apcore_toolkit.types import ScannedModule diff --git a/toolkit/python/src/apcore_toolkit/types.py b/toolkit/python/src/apcore_toolkit/types.py index ce33865b..275aedc3 100644 --- a/toolkit/python/src/apcore_toolkit/types.py +++ b/toolkit/python/src/apcore_toolkit/types.py @@ -10,7 +10,7 @@ from dataclasses import dataclass, field, replace from typing import Any -from apcore import ModuleAnnotations, ModuleExample +from apcore.module import ModuleAnnotations, ModuleExample @dataclass diff --git a/toolkit/rust/Cargo.lock b/toolkit/rust/Cargo.lock index cda7b630..fa5609bd 100644 --- a/toolkit/rust/Cargo.lock +++ b/toolkit/rust/Cargo.lock @@ -48,9 +48,9 @@ checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" [[package]] name = "apcore" -version = "1.0.0-alpha.1" +version = "1.0.0-alpha.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bbc1db3680f3d81b7096fa5eb70476a2c043b333681c2a7bba3597a49bbf11f6" +checksum = "54e630a6f3c82ee9e01aec1f58ad14a06e21d8082414a1f4d398bce2f45b4de3" dependencies = [ "async-stream", "async-trait", @@ -59,14 +59,12 @@ dependencies = [ "futures-core", "futures-util", "jsonschema", - "notify", "parking_lot", "referencing", "regex", "schemars", "serde", "serde_json", - "serde_yaml_ng", "sha2", "thiserror", "tokio", @@ -76,7 +74,7 @@ dependencies = [ [[package]] name = "apcore-toolkit" -version = "0.15.1-alpha.1" +version = "0.15.1-alpha.2" dependencies = [ "apcore", "async-trait", @@ -509,15 +507,6 @@ dependencies = [ "num", ] -[[package]] -name = "fsevent-sys" -version = "4.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "76ee7a02da4d231650c7cea31349b889be2f45ddb3ef3032d2ec8185f6313fd2" -dependencies = [ - "libc", -] - [[package]] name = "futures" version = "0.3.32" @@ -972,26 +961,6 @@ dependencies = [ "serde_core", ] -[[package]] -name = "inotify" -version = "0.11.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bd5b3eaf1a28b758ac0faa5a4254e8ab2705605496f1b1f3fbbc3988ad73d199" -dependencies = [ - "bitflags", - "inotify-sys", - "libc", -] - -[[package]] -name = "inotify-sys" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e05c02b5e89bff3b946cedeca278abc628fe811e604f027c45a8aa3cf793d0eb" -dependencies = [ - "libc", -] - [[package]] name = "ipnet" version = "2.12.0" @@ -1050,26 +1019,6 @@ dependencies = [ "uuid-simd", ] -[[package]] -name = "kqueue" -version = "1.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eac30106d7dce88daf4a3fcb4879ea939476d5074a9b7ddd0fb97fa4bed5596a" -dependencies = [ - "kqueue-sys", - "libc", -] - -[[package]] -name = "kqueue-sys" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a7b65860415f949f23fa882e669f2dbd4a0f0eeb1acdd56790b30494afd7da2f" -dependencies = [ - "bitflags", - "libc", -] - [[package]] name = "lazy_static" version = "1.5.0" @@ -1150,7 +1099,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "50b7e5b27aa02a74bac8c3f23f448f8d87ff11f92d3aac1a6ed369ee08cc56c1" dependencies = [ "libc", - "log", "wasi", "windows-sys 0.61.2", ] @@ -1172,33 +1120,6 @@ dependencies = [ "tempfile", ] -[[package]] -name = "notify" -version = "8.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4d3d07927151ff8575b7087f245456e549fea62edf0ec4e565a5ee50c8402bc3" -dependencies = [ - "bitflags", - "fsevent-sys", - "inotify", - "kqueue", - "libc", - "log", - "mio", - "notify-types", - "walkdir", - "windows-sys 0.60.2", -] - -[[package]] -name = "notify-types" -version = "2.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "42b8cfee0e339a0337359f3c88165702ac6e600dc01c0cc9579a92d62b08477a" -dependencies = [ - "bitflags", -] - [[package]] name = "num" version = "0.4.3" @@ -2475,16 +2396,7 @@ version = "0.52.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" dependencies = [ - "windows-targets 0.52.6", -] - -[[package]] -name = "windows-sys" -version = "0.60.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb" -dependencies = [ - "windows-targets 0.53.5", + "windows-targets", ] [[package]] @@ -2502,31 +2414,14 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" dependencies = [ - "windows_aarch64_gnullvm 0.52.6", - "windows_aarch64_msvc 0.52.6", - "windows_i686_gnu 0.52.6", - "windows_i686_gnullvm 0.52.6", - "windows_i686_msvc 0.52.6", - "windows_x86_64_gnu 0.52.6", - "windows_x86_64_gnullvm 0.52.6", - "windows_x86_64_msvc 0.52.6", -] - -[[package]] -name = "windows-targets" -version = "0.53.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4945f9f551b88e0d65f3db0bc25c33b8acea4d9e41163edf90dcd0b19f9069f3" -dependencies = [ - "windows-link", - "windows_aarch64_gnullvm 0.53.1", - "windows_aarch64_msvc 0.53.1", - "windows_i686_gnu 0.53.1", - "windows_i686_gnullvm 0.53.1", - "windows_i686_msvc 0.53.1", - "windows_x86_64_gnu 0.53.1", - "windows_x86_64_gnullvm 0.53.1", - "windows_x86_64_msvc 0.53.1", + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", ] [[package]] @@ -2535,96 +2430,48 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" -[[package]] -name = "windows_aarch64_gnullvm" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a9d8416fa8b42f5c947f8482c43e7d89e73a173cead56d044f6a56104a6d1b53" - [[package]] name = "windows_aarch64_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" -[[package]] -name = "windows_aarch64_msvc" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b9d782e804c2f632e395708e99a94275910eb9100b2114651e04744e9b125006" - [[package]] name = "windows_i686_gnu" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" -[[package]] -name = "windows_i686_gnu" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "960e6da069d81e09becb0ca57a65220ddff016ff2d6af6a223cf372a506593a3" - [[package]] name = "windows_i686_gnullvm" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" -[[package]] -name = "windows_i686_gnullvm" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fa7359d10048f68ab8b09fa71c3daccfb0e9b559aed648a8f95469c27057180c" - [[package]] name = "windows_i686_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" -[[package]] -name = "windows_i686_msvc" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e7ac75179f18232fe9c285163565a57ef8d3c89254a30685b57d83a38d326c2" - [[package]] name = "windows_x86_64_gnu" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" -[[package]] -name = "windows_x86_64_gnu" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c3842cdd74a865a8066ab39c8a7a473c0778a3f29370b5fd6b4b9aa7df4a499" - [[package]] name = "windows_x86_64_gnullvm" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" -[[package]] -name = "windows_x86_64_gnullvm" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0ffa179e2d07eee8ad8f57493436566c7cc30ac536a3379fdf008f47f6bb7ae1" - [[package]] name = "windows_x86_64_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" -[[package]] -name = "windows_x86_64_msvc" -version = "0.53.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650" - [[package]] name = "wit-bindgen" version = "0.51.0" diff --git a/toolkit/rust/Cargo.toml b/toolkit/rust/Cargo.toml index 9352fae2..3b7fcb24 100644 --- a/toolkit/rust/Cargo.toml +++ b/toolkit/rust/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "apcore-toolkit" -version = "0.15.1-alpha.1" +version = "0.15.1-alpha.2" edition = "2021" description = "Shared scanner, schema extraction, and output toolkit for apcore framework adapters" license = "Apache-2.0" @@ -21,7 +21,7 @@ all-features = true rustdoc-args = ["--cfg", "docsrs"] [dependencies] -apcore = ">=0.33.0, <=1.0.0-alpha.1" +apcore = { version = ">=0.33.0, <=1.0.0-alpha.2", default-features = false } serde = { version = "1", features = ["derive"] } # `preserve_order` is required for the toolkit's byte-equivalent tabular # formatters (csv / jsonl): object key order MUST match insertion order to diff --git a/toolkit/typescript/package.json b/toolkit/typescript/package.json index b6e81a68..c7a27c4c 100644 --- a/toolkit/typescript/package.json +++ b/toolkit/typescript/package.json @@ -1,6 +1,6 @@ { "name": "apcore-toolkit", - "version": "0.15.1-alpha.1", + "version": "0.15.1-alpha.2", "description": "Shared scanner, schema extraction, and output toolkit for apcore framework adapters", "type": "module", "main": "./dist/index.js", @@ -57,7 +57,7 @@ }, "dependencies": { "ajv": "^8.17.0", - "apcore-js": ">=0.33.0 <1.0.0 || 1.0.0-alpha.1", + "apcore-js": ">=0.33.0 <1.0.0 || 1.0.0-alpha.2", "js-yaml": "^4.3.2" }, "peerDependencies": { diff --git a/toolkit/typescript/pnpm-lock.yaml b/toolkit/typescript/pnpm-lock.yaml index 8b711c8f..98f31559 100644 --- a/toolkit/typescript/pnpm-lock.yaml +++ b/toolkit/typescript/pnpm-lock.yaml @@ -15,7 +15,7 @@ importers: specifier: ^8.17.0 version: 8.20.0 apcore-js: - specifier: '>=0.33.0 <1.0.0 || 1.0.0-alpha.1' + specifier: '>=0.33.0 <1.0.0 || 1.0.0-alpha.2' version: 0.33.0 js-yaml: specifier: ^4.3.2 From d83b770b49470057cc01da3e1822cfa351dbca09 Mon Sep 17 00:00:00 2001 From: tercel Date: Fri, 27 Nov 2026 17:40:29 +0800 Subject: [PATCH 7/9] ci: verify Surfaces with pinned alpha.2 Core distributions Signed-off-by: tercel --- .github/workflows/core-candidate.yml | 74 +++++++++++++-------------- .github/workflows/python.yml | 24 ++++++++- .github/workflows/rust.yml | 6 +-- .github/workflows/typescript.yml | 59 ++++++++++++++------- scripts/verify-rust-core-candidate.py | 14 +++-- 5 files changed, 110 insertions(+), 67 deletions(-) diff --git a/.github/workflows/core-candidate.yml b/.github/workflows/core-candidate.yml index 5bab1d3a..42b2b127 100644 --- a/.github/workflows/core-candidate.yml +++ b/.github/workflows/core-candidate.yml @@ -93,7 +93,7 @@ jobs: exit 1 fi if [[ -n "$EXPECTED_CORE_SHA" && "$head_sha" != "$EXPECTED_CORE_SHA" ]]; then - echo "The Core run did not build the reviewed alpha.1 commit." >&2 + echo "The Core run did not build the requested candidate commit." >&2 exit 1 fi example_sha="${EXPECTED_EXAMPLE_SHA:-$head_sha}" @@ -115,6 +115,13 @@ jobs: matrix: component: [toolkit, mcp, a2a, cli] core: [minimum, candidate] + exclude: &candidate-only-hosts + - component: mcp + core: minimum + - component: a2a + core: minimum + - component: cli + core: minimum defaults: run: working-directory: ${{ matrix.component }}/python @@ -194,7 +201,7 @@ jobs: assert core_path == installed.locate_file("apcore/__init__.py").resolve() assert toolkit_path == toolkit_expected.resolve() if os.environ["CORE_MODE"] == "candidate": - assert installed.version == "1.0.0a1" + assert installed.version == "1.0.0a2" origin = json.loads(installed.read_text("direct_url.json") or "{}") assert origin.get("url") == Path(os.environ["CORE_INSTALL"]).resolve().as_uri() assert callable(getattr(Executor, "stream_with_completion", None)) @@ -234,6 +241,7 @@ jobs: matrix: component: [toolkit, mcp, a2a, cli] core: [minimum, candidate] + exclude: *candidate-only-hosts defaults: run: working-directory: ${{ matrix.component }}/typescript @@ -267,27 +275,6 @@ jobs: env: EXPECTED_SHA256: ${{ inputs.npm_sha256 }} run: | - toolkit="$GITHUB_WORKSPACE/toolkit/typescript" - roots=("$PWD") - if [[ "$COMPONENT" == toolkit ]]; then - pnpm install --frozen-lockfile - else - pnpm --dir "$toolkit" install --frozen-lockfile - # The release lock refers to the registry package. Test the candidate - # sources before that package is published by using a local override. - TOOLKIT="$toolkit" node --input-type=module <<'JS' - import { readFileSync, writeFileSync } from 'node:fs'; - - const file = 'package.json'; - const manifest = JSON.parse(readFileSync(file, 'utf8')); - manifest.pnpm ??= {}; - manifest.pnpm.overrides ??= {}; - manifest.pnpm.overrides['apcore-toolkit'] = 'link:' + process.env.TOOLKIT; - writeFileSync(file, JSON.stringify(manifest, null, 2) + '\n'); - JS - pnpm install --no-frozen-lockfile - roots+=("$toolkit") - fi core_package="apcore-js@0.33.0" if [[ "$CORE_MODE" == candidate ]]; then shopt -s nullglob @@ -309,14 +296,29 @@ jobs: installed=$(mktemp -d) npm install --prefix "$installed" --ignore-scripts --no-save --no-package-lock --no-audit --no-fund "$core_package" core_root="$installed/node_modules/apcore-js" - for root in "${roots[@]}"; do - rm -f "$root/node_modules/apcore-js" - ln -s "$core_root" "$root/node_modules/apcore-js" - done + toolkit="$GITHUB_WORKSPACE/toolkit/typescript" + roots=("$toolkit") if [[ "$COMPONENT" != toolkit ]]; then - pnpm --dir "$toolkit" build + roots+=("$PWD") fi - pnpm build + for root in "${roots[@]}"; do + CORE_ROOT="$core_root" TOOLKIT_ROOT="$toolkit" ROOT="$root" node --input-type=module <<'JS' + import { readFileSync, writeFileSync } from 'node:fs'; + import { join } from 'node:path'; + + const file = join(process.env.ROOT, 'package.json'); + const manifest = JSON.parse(readFileSync(file, 'utf8')); + manifest.pnpm ??= {}; + const overrides = manifest.pnpm.overrides ??= {}; + overrides['apcore-js'] = 'link:' + process.env.CORE_ROOT; + if (process.env.ROOT !== process.env.TOOLKIT_ROOT) { + overrides['apcore-toolkit'] = 'link:' + process.env.TOOLKIT_ROOT; + } + writeFileSync(file, JSON.stringify(manifest, null, 2) + '\n'); + JS + pnpm --dir "$root" install --no-frozen-lockfile + pnpm --dir "$root" build + done for root in "${roots[@]}"; do ( cd "$root" @@ -338,7 +340,7 @@ jobs: assert.ok(coreEntry.startsWith(core + sep)); assert.equal(toolkitEntry, realpathSync(resolve(process.env.TOOLKIT_ROOT, 'dist/index.js'))); if (process.env.CORE_MODE === 'candidate') { - assert.equal(coreVersion, '1.0.0-alpha.1'); + assert.equal(coreVersion, '1.0.0-alpha.2'); assert.equal(typeof Executor.prototype.streamWithCompletion, 'function'); assert.equal(typeof APCore.prototype.streamWithCompletion, 'function'); } else { @@ -361,13 +363,7 @@ jobs: matrix: component: [toolkit, mcp, a2a, cli] core: [minimum, candidate] - # For C2-required packages, the first alpha is both the minimum and - # the current candidate. The candidate entry covers both. - exclude: - - component: mcp - core: minimum - - component: cli - core: minimum + exclude: *candidate-only-hosts env: CORE_MODE: ${{ matrix.core }} COMPONENT: ${{ matrix.component }} @@ -410,8 +406,8 @@ jobs: crate="${crates[0]}" version="${crate##*/apcore-}" version="${version%.crate}" - if [[ "$version" != 1.0.0-alpha.1 ]]; then - echo "Expected the alpha.1 Core crate." >&2 + if [[ "$version" != 1.0.0-alpha.2 ]]; then + echo "Expected the alpha.2 Core crate." >&2 exit 1 fi if [[ "$CORE_MODE" == candidate && -n "$EXPECTED_SHA256" ]]; then diff --git a/.github/workflows/python.yml b/.github/workflows/python.yml index 4c1674f0..f0df6a2c 100644 --- a/.github/workflows/python.yml +++ b/.github/workflows/python.yml @@ -14,6 +14,9 @@ on: permissions: contents: read +env: + CORE_REF: dc61dd575a3d76a113f55a84175b6f36ba35e894 + jobs: test: name: Python ${{ matrix.version }} (${{ matrix.component }}) @@ -31,16 +34,31 @@ jobs: working-directory: ${{ matrix.component }}/python steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 + - &checkout-core + uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 + with: + repository: aiperceivable/apcore + ref: ${{ env.CORE_REF }} + path: .ci-apcore-core + persist-credentials: false - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 with: python-version: ${{ matrix.version }} + - &build-core-wheel + name: Build the in-review Core wheel + run: | + python -m pip install build + python -m build --wheel --outdir "$RUNNER_TEMP/core-wheel" "$GITHUB_WORKSPACE/.ci-apcore-core/python" - name: Install and verify local dependencies shell: bash run: | - args=(-e '.[dev]') + args=("$RUNNER_TEMP"/core-wheel/apcore-*.whl -e '.[dev]') if [[ "${{ matrix.component }}" != toolkit ]]; then args+=(-e "$GITHUB_WORKSPACE/toolkit/python") fi + if [[ "${{ matrix.component }}" == a2a ]]; then + args+=(aiohttp) + fi if [[ -f constraints.txt ]]; then args+=(-c constraints.txt) fi @@ -68,9 +86,11 @@ jobs: working-directory: ${{ matrix.component }}/python steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 + - *checkout-core - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 with: python-version: '3.12' + - *build-core-wheel - name: Build wheel and sdist run: | python -m pip install build @@ -80,7 +100,7 @@ jobs: env: COMPONENT: ${{ matrix.component }} run: | - wheels=( "$PWD"/dist/*.whl ) + wheels=( "$PWD"/dist/*.whl "$RUNNER_TEMP"/core-wheel/apcore-*.whl ) temporary=$(mktemp -d) if [[ "$COMPONENT" == a2a || "$COMPONENT" == cli ]]; then python -m build --wheel --outdir "$temporary/wheels" "$GITHUB_WORKSPACE/toolkit/python" diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml index 271754d3..ee3d1e2f 100644 --- a/.github/workflows/rust.yml +++ b/.github/workflows/rust.yml @@ -22,9 +22,9 @@ permissions: env: # The released lockfiles already reference these prereleases. Bootstrap CI # from the reviewed Core commit while those versions are unpublished. - CORE_REF: b28e1bfd01b804c8662e9e418d8487d0e08cc0ce - CORE_CRATE_VERSION: 1.0.0-alpha.1 - CORE_CRATE_SHA256: bbc1db3680f3d81b7096fa5eb70476a2c043b333681c2a7bba3597a49bbf11f6 + CORE_REF: 0384a3d4e7688c47eaa1feea6032fb4739813f20 + CORE_CRATE_VERSION: 1.0.0-alpha.2 + CORE_CRATE_SHA256: 54e630a6f3c82ee9e01aec1f58ad14a06e21d8082414a1f4d398bce2f45b4de3 jobs: source: diff --git a/.github/workflows/typescript.yml b/.github/workflows/typescript.yml index 0f1896b0..4dd96bb9 100644 --- a/.github/workflows/typescript.yml +++ b/.github/workflows/typescript.yml @@ -14,6 +14,9 @@ on: permissions: contents: read +env: + CORE_REF: 0384a3d4e7688c47eaa1feea6032fb4739813f20 + jobs: test: name: TypeScript (${{ matrix.component }}) @@ -27,41 +30,57 @@ jobs: working-directory: ${{ matrix.component }}/typescript steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 + - &checkout-core + uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 + with: + repository: aiperceivable/apcore + ref: ${{ env.CORE_REF }} + path: .ci-apcore-core + persist-credentials: false - uses: actions/setup-node@v4 with: node-version: '22' - uses: pnpm/action-setup@v4 with: version: '10.30.1' + - &build-core-npm + name: Build the in-review Core npm distribution + run: | + core="$GITHUB_WORKSPACE/.ci-apcore-core/typescript" + pnpm --dir "$core" install --frozen-lockfile + pnpm --dir "$core" build + pnpm --dir "$core" pack --pack-destination "$RUNNER_TEMP" - &install-dependencies - name: Install dependencies with the checkout's Toolkit + name: Install dependencies with the Core archive and checkout Toolkit shell: bash run: | toolkit="$GITHUB_WORKSPACE/toolkit/typescript" - if [[ "$PWD" == "$toolkit" ]]; then - pnpm install --frozen-lockfile - exit - fi - - pnpm --dir "$toolkit" install --frozen-lockfile - pnpm --dir "$toolkit" build - - # Use the local Toolkit before pnpm attempts to fetch the registry - # artifact. Restore both inputs before running build or pack. - saved=$(mktemp -d) - cp package.json pnpm-lock.yaml "$saved/" - trap 'cp "$saved/package.json" "$saved/pnpm-lock.yaml" .; rm -rf "$saved"' EXIT - TOOLKIT="$toolkit" node --input-type=module <<'JS' + archive=( "$RUNNER_TEMP"/apcore-js-*.tgz ) + installed=$(mktemp -d) + npm install --prefix "$installed" --ignore-scripts --no-save --no-package-lock "${archive[0]}" + core_root="$installed/node_modules/apcore-js" + install_deps() ( + cd "$1" + saved=$(mktemp -d) + cp package.json pnpm-lock.yaml "$saved/" + trap 'cp "$saved/package.json" "$saved/pnpm-lock.yaml" .; rm -rf "$saved"' EXIT + CORE_ROOT="$core_root" TOOLKIT="$toolkit" node --input-type=module <<'JS' import { readFileSync, writeFileSync } from 'node:fs'; const file = 'package.json'; const manifest = JSON.parse(readFileSync(file, 'utf8')); manifest.pnpm ??= {}; - manifest.pnpm.overrides ??= {}; - manifest.pnpm.overrides['apcore-toolkit'] = 'link:' + process.env.TOOLKIT; + const overrides = manifest.pnpm.overrides ??= {}; + overrides['apcore-js'] = 'link:' + process.env.CORE_ROOT; + if (process.cwd() !== process.env.TOOLKIT) overrides['apcore-toolkit'] = 'link:' + process.env.TOOLKIT; writeFileSync(file, JSON.stringify(manifest, null, 2) + '\n'); JS - pnpm install --no-frozen-lockfile + pnpm install --no-frozen-lockfile + ) + install_deps "$toolkit" + if [[ "$PWD" == "$toolkit" ]]; then exit; fi + pnpm --dir "$toolkit" build + install_deps "$PWD" TOOLKIT="$toolkit" node --input-type=module <<'JS' import assert from 'node:assert/strict'; import { realpathSync } from 'node:fs'; @@ -100,12 +119,14 @@ jobs: working-directory: ${{ matrix.component }}/typescript steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 + - *checkout-core - uses: actions/setup-node@v4 with: node-version: '22' - uses: pnpm/action-setup@v4 with: version: '10.30.1' + - *build-core-npm - *install-dependencies - run: pnpm build - name: Pack and install as an external consumer @@ -119,7 +140,7 @@ jobs: toolkit="$GITHUB_WORKSPACE/toolkit/typescript" pnpm --dir "$toolkit" pack --pack-destination "$temporary" fi - archives=( "$temporary"/*.tgz ) + archives=( "$temporary"/*.tgz "$RUNNER_TEMP"/apcore-js-*.tgz ) toolkit_archive=( "$temporary"/apcore-toolkit-*.tgz ) cd "$temporary" npm init -y diff --git a/scripts/verify-rust-core-candidate.py b/scripts/verify-rust-core-candidate.py index 19437212..84535d05 100644 --- a/scripts/verify-rust-core-candidate.py +++ b/scripts/verify-rust-core-candidate.py @@ -19,15 +19,21 @@ def package_name(manifest: Path) -> str: def pin_core(manifest: Path, version: str) -> None: + original = manifest.read_text() + dependency = tomllib.loads(original)["dependencies"]["apcore"] + if isinstance(dependency, str): + pattern = r'^(apcore\s*=\s*")[^"]+(")$' + else: + pattern = r'^(apcore\s*=\s*\{[^\n}]*\bversion\s*=\s*")[^"]+("[^\n}]*\})$' text, count = re.subn( - r'^apcore = "[^"]+"$', - f'apcore = "={version}"', - manifest.read_text(), + pattern, + lambda match: f"{match[1]}={version}{match[2]}", + original, count=1, flags=re.MULTILINE, ) if count != 1: - raise ValueError(f"Expected a version-only apcore dependency in {manifest}") + raise ValueError(f"Expected a versioned apcore dependency in {manifest}") manifest.write_text(text) From 8b3ffa471b49e59b9c5f677eebc0fc2577f48e12 Mon Sep 17 00:00:00 2001 From: tercel Date: Fri, 27 Nov 2026 17:42:47 +0800 Subject: [PATCH 8/9] docs(rust): record alpha.2 build requirements Signed-off-by: tercel --- cli/rust/README.md | 2 +- mcp/rust/README.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/cli/rust/README.md b/cli/rust/README.md index 86663d70..18250300 100644 --- a/cli/rust/README.md +++ b/cli/rust/README.md @@ -48,7 +48,7 @@ Terminal adapter for apcore. Execute AI-Perceivable modules from the command lin cargo install apcore-cli ``` -Build with current stable Rust (`apcore` requires Rust 1.86+, and the checked-in lockfile includes dependencies requiring Rust 1.88+), `apcore = 1.0.0-alpha.1`, and `apcore-toolkit = 0.15.1-alpha.1` with `http-proxy`. Registry-based installation requires a compatible APCore release on crates.io. When testing a locally unpacked prerelease, resolve both this crate and Toolkit against the same unpacked APCore package and confirm with `cargo metadata`. +Build with a stable Rust toolchain that supports the lockfile's dependencies (Rust 1.88 or later). This candidate uses `apcore = 1.0.0-alpha.2` with the `config` feature and `apcore-toolkit = 0.15.1-alpha.2` with `http-proxy`. For a local prerelease build, use the same APCore crate for the CLI and Toolkit. Check the selected versions with `cargo metadata`. > **Note:** `apcore-toolkit-rust` 0.7.0 enables `serde_json/preserve_order`. This transitively affects all `serde_json::Map` iteration in your dependency tree — code that relied on alphabetical key ordering must re-sort explicitly. diff --git a/mcp/rust/README.md b/mcp/rust/README.md index b2cfb9f6..359c7fd7 100644 --- a/mcp/rust/README.md +++ b/mcp/rust/README.md @@ -60,7 +60,7 @@ cargo add apcore-mcp cargo install apcore-mcp ``` -Requires Rust 1.86+, `apcore = 1.0.0-alpha.1` and `apcore-toolkit = 0.15.1-alpha.1`. +Requires Rust 1.86 or later, `apcore = 1.0.0-alpha.2` with `config` and `sys-modules`, and `apcore-toolkit = 0.15.1-alpha.2`. Registry-based installation requires a compatible APCore release on crates.io. When testing a locally unpacked prerelease, resolve both this crate and Toolkit against the same unpacked APCore package and confirm with `cargo metadata`. From 48b9eec18a1de94453e55c74b036b5c65c3213a7 Mon Sep 17 00:00:00 2001 From: tercel Date: Fri, 27 Nov 2026 20:03:07 +0800 Subject: [PATCH 9/9] test(surfaces): align alpha.2 checks with Core contracts Signed-off-by: tercel --- .github/workflows/python.yml | 2 +- .github/workflows/typescript.yml | 2 +- a2a/docs/spec/srs.md | 2 +- a2a/python/src/apcore_a2a/server/factory.py | 13 +++--- a2a/rust/src/apcore_a2a.rs | 11 +++-- a2a/typescript/src/server/factory.ts | 13 +++--- .../tests/server/system-modules.test.ts | 42 ++++++++++++------- mcp/docs/features/openai-converter.md | 2 +- mcp/docs/features/schema-converter.md | 19 ++++----- mcp/docs/srs-apcore-mcp.md | 10 ++--- mcp/docs/tech-design-apcore-mcp.md | 19 +++++---- mcp/docs/test-plan-apcore-mcp.md | 2 +- .../tests/integration/test_integration.py | 18 ++++---- 13 files changed, 81 insertions(+), 74 deletions(-) diff --git a/.github/workflows/python.yml b/.github/workflows/python.yml index f0df6a2c..5115d1ec 100644 --- a/.github/workflows/python.yml +++ b/.github/workflows/python.yml @@ -15,7 +15,7 @@ permissions: contents: read env: - CORE_REF: dc61dd575a3d76a113f55a84175b6f36ba35e894 + CORE_REF: 3b5fb5defb7e32900da4e826a848bb23258cd91e jobs: test: diff --git a/.github/workflows/typescript.yml b/.github/workflows/typescript.yml index 4dd96bb9..d709282e 100644 --- a/.github/workflows/typescript.yml +++ b/.github/workflows/typescript.yml @@ -15,7 +15,7 @@ permissions: contents: read env: - CORE_REF: 0384a3d4e7688c47eaa1feea6032fb4739813f20 + CORE_REF: 3b5fb5defb7e32900da4e826a848bb23258cd91e jobs: test: diff --git a/a2a/docs/spec/srs.md b/a2a/docs/spec/srs.md index e426aa8d..e9ac75f0 100644 --- a/a2a/docs/spec/srs.md +++ b/a2a/docs/spec/srs.md @@ -483,7 +483,7 @@ The ACL SHALL be consulted with **no arguments projection**, because a card is d **Description:** At server construction, the system SHALL read apcore's `Executor.governance_state()` (`governanceState()` in TypeScript) and, when `unprotected_control_surface` is `true`, emit a warning naming the condition. The system SHALL NOT refuse to start, and SHALL NOT alter the card on account of the flag. -**Rationale:** `system.control.*` modules are annotated `requires_approval`, but apcore's approval gate warns once and continues when no `ApprovalHandler` is configured, failing closed only under `ExecutionPolicy(strict=True)`. So a deployment with `sys_modules.events` enabled, no `acl/` directory and no approval handler has write modules that nothing gates — and FR-AGC-003 criterion 12 removes them from the *card* without removing them from the *dispatch table*. Visibility and invocability are separate questions with separate answers, and the card rule must not be mistaken for a fix to the second. +**Rationale** — The Core default approval gate denies calls to `system.control.*` modules that require approval when no `ApprovalHandler` is configured. An explicit non-strict policy without an ACL or a strategy without governance gates can leave controls unprotected. FR-AGC-003 criterion 12 omits these modules from the public card while their dispatch routes remain registered. `governance_state()` is the accessor apcore added for exactly this (apcore `PROTOCOL_SPEC` §6.6.5). It answers "is a gate *engaging*", not "is an ACL *attached*" — the ACL and approval gates are pipeline *steps*, and the `internal`, `testing` and `minimal` strategies remove them, so an executor can hold an ACL that no step ever consults. Re-deriving the question per binding from the raw `acl` / `approval_handler` fields would answer the wrong one, and only apcore-rust exposes those fields anyway. apcore made the accessor a **pure read** and left the reaction to the caller, naming "a serve-time adapter may warn or refuse" as the two options; warning is the reaction this project takes, for the reason FR-AGC-003 gives for not refusing. diff --git a/a2a/python/src/apcore_a2a/server/factory.py b/a2a/python/src/apcore_a2a/server/factory.py index 691bf809..52755c65 100644 --- a/a2a/python/src/apcore_a2a/server/factory.py +++ b/a2a/python/src/apcore_a2a/server/factory.py @@ -288,13 +288,12 @@ def _warn_on_unprotected_control_surface(executor: Any) -> None: from the raw ``acl`` / ``approval_handler`` attributes would answer the wrong one. - Withholding ``system.*`` from the public card (FR-AGC-003 criterion 12) - removes the surface from *discovery*, not from *dispatch*: apcore's approval - gate warns once and continues when no ``ApprovalHandler`` is configured, so - the write modules stay callable. This warning exists so the card rule cannot - be mistaken for a fix to that. apcore deliberately made the accessor a pure - read and left the reaction to the adapter; warning is the reaction, and a - failure to read it must never stop a server from starting. + The public Agent Card omits ``system.*`` (FR-AGC-003 criterion 12). + Registered controls still have dispatch routes. Core's default approval + gate fails closed for annotated controls without a handler. Explicit + non-strict policies or strategies without governance gates can leave + controls unprotected. + A failure to read the diagnostic must never stop a server from starting. """ accessor = getattr(executor, "governance_state", None) if not callable(accessor): diff --git a/a2a/rust/src/apcore_a2a.rs b/a2a/rust/src/apcore_a2a.rs index 9fe964f8..7d8e9b38 100644 --- a/a2a/rust/src/apcore_a2a.rs +++ b/a2a/rust/src/apcore_a2a.rs @@ -440,12 +440,11 @@ pub fn bind_addr(config: &APCoreA2AConfig) -> Result { /// ever consults. This crate has `Executor::acl` right there as a public field /// and reading it would answer the wrong question. /// -/// Withholding `system.*` from the public card (FR-AGC-003 criterion 12) removes -/// the surface from *discovery*, not from *dispatch*: apcore's approval gate -/// warns once and continues when no `ApprovalHandler` is configured, so the write -/// modules stay callable. This warning exists so the card rule cannot be mistaken -/// for a fix to that. apcore deliberately made the accessor a pure read and left -/// the reaction to the adapter; warning is the reaction. +/// The public Agent Card omits `system.*` (FR-AGC-003 criterion 12). +/// Registered controls still have dispatch routes. Core's default approval +/// gate fails closed for annotated controls without a handler. Explicit +/// non-strict policies or strategies without governance gates can leave +/// controls unprotected. fn warn_on_unprotected_control_surface(executor: &apcore::Executor) { if executor.governance_state().unprotected_control_surface { tracing::warn!( diff --git a/a2a/typescript/src/server/factory.ts b/a2a/typescript/src/server/factory.ts index bfc8c01c..87a54869 100644 --- a/a2a/typescript/src/server/factory.ts +++ b/a2a/typescript/src/server/factory.ts @@ -142,13 +142,12 @@ interface GovernanceStateLike { * ever consults. Re-deriving the question from the raw `acl` / `approvalHandler` * fields would answer the wrong one, and apcore-js does not expose them anyway. * - * Withholding `system.*` from the public card (FR-AGC-003 criterion 12) removes - * the surface from *discovery*, not from *dispatch*: apcore's approval gate warns - * once and continues when no `ApprovalHandler` is configured, so the write - * modules stay callable. This warning exists so the card rule cannot be mistaken - * for a fix to that. apcore deliberately made the accessor a pure read and left - * the reaction to the adapter; warning is the reaction, and a failure to read it - * must never stop a server from starting. + * The public Agent Card omits `system.*` (FR-AGC-003 criterion 12). + * Registered controls still have dispatch routes. Core's default approval + * gate fails closed for annotated controls without a handler. Explicit + * non-strict policies or strategies without governance gates can leave + * controls unprotected. + * A failure to read the diagnostic must never stop a server from starting. */ function warnOnUnprotectedControlSurface(executor: unknown): void { const accessor = (executor as { governanceState?: () => GovernanceStateLike } | null) diff --git a/a2a/typescript/tests/server/system-modules.test.ts b/a2a/typescript/tests/server/system-modules.test.ts index 2d76d9f8..2bf016c9 100644 --- a/a2a/typescript/tests/server/system-modules.test.ts +++ b/a2a/typescript/tests/server/system-modules.test.ts @@ -12,7 +12,7 @@ * without an `acl/` directory has no ACL at all. */ import { describe, it, expect, vi, afterEach } from "vitest"; -import { Registry, Executor, module as apcoreModule } from "apcore-js"; +import { ExecutionPolicy, Executor, Registry, module as apcoreModule } from "apcore-js"; import { Config } from "apcore-js/config"; import { registerSysModules } from "apcore-js/sys-modules"; import { Type } from "@sinclair/typebox"; @@ -38,6 +38,14 @@ function registryWithAUserModule(): Registry { return registry; } +function registerControlModules(registry: Registry, executor: Executor): void { + registerSysModules( + registry, + executor, + new Config({ sys_modules: { enabled: true, events: { enabled: true } } }), + ); +} + const systemIds = (registry: Registry): string[] => registry .list() @@ -78,20 +86,12 @@ describe("apcore system.* modules", () => { expect((agentCard.skills ?? []).map((s) => s.id)).toEqual(["math.add"]); }); - it("warns when the control surface is unprotected", () => { - // srs FR-AGC-007 criterion 2, reached the way a real deployment reaches it: - // the operator builds their own apcore stack with sys_modules.events enabled - // — which is what registers the three system.control.* write modules — and - // hands the Executor to this package. apcore's approval gate warns once and - // continues with no ApprovalHandler, so those modules stay callable even - // though FR-AGC-003 criterion 12 keeps them off the card. + it("warns when an explicit non-strict approval policy leaves controls unprotected", () => { + // srs FR-AGC-007 criterion 2. A non-strict policy allows the annotated + // controls to execute without an approval handler or an ACL. const registry = registryWithAUserModule(); - const executor = new Executor({ registry }); - registerSysModules( - registry, - executor, - new Config({ sys_modules: { enabled: true, events: { enabled: true } } }), - ); + const executor = new Executor({ registry, policy: new ExecutionPolicy(null, { strict: false }) }); + registerControlModules(registry, executor); expect(executor.governanceState().unprotectedControlSurface).toBe(true); const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); @@ -103,6 +103,20 @@ describe("apcore system.* modules", () => { expect((agentCard.skills ?? []).map((s) => s.id)).toEqual(["math.add"]); }); + it("stays quiet when the default approval policy protects the controls", () => { + const registry = registryWithAUserModule(); + const executor = new Executor({ registry }); + registerControlModules(registry, executor); + expect(executor.governanceState()).toMatchObject({ + controlModulesRegistered: true, + unprotectedControlSurface: false, + }); + + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + create(registry, executor); + expect(warn.mock.calls.map((call) => String(call[0])).join("\n")).not.toContain("system.control"); + }); + it("stays quiet when only the read modules are registered", () => { // srs FR-AGC-007 criterion 3. const registry = registryWithAUserModule(); diff --git a/mcp/docs/features/openai-converter.md b/mcp/docs/features/openai-converter.md index c05dd7ba..0b211239 100644 --- a/mcp/docs/features/openai-converter.md +++ b/mcp/docs/features/openai-converter.md @@ -44,7 +44,7 @@ The OpenAI Converter transforms apcore modules into OpenAI-compatible tool defin - **List[Dict[str, Any]]** (OpenAI API) — A list of dictionaries ready to be passed to the OpenAI SDK. ### Dependencies -- **Schema Converter** — Used to resolve and inline schema references. +- **Schema Converter** — Normalizes the root input schema and retains local references and definitions. - **Annotation Mapper** — Used to generate the description suffix. ## Data Flow diff --git a/mcp/docs/features/schema-converter.md b/mcp/docs/features/schema-converter.md index 5e4818b7..8da66d48 100644 --- a/mcp/docs/features/schema-converter.md +++ b/mcp/docs/features/schema-converter.md @@ -1,5 +1,5 @@ --- -description: "Schema Converter feature spec: inlines $ref/$defs from apcore Pydantic JSON Schemas into self-contained MCP inputSchema/OpenAI parameters with root object normalization and 32-level cycle detection." +description: "Schema Converter normalizes JSON Schema roots and supports explicit local reference inlining with a 32-level depth limit." --- # Schema Converter @@ -10,12 +10,12 @@ description: "Schema Converter feature spec: inlines $ref/$defs from apcore Pyda ## Purpose -The Schema Converter is responsible for transforming apcore JSON Schema definitions (produced by Pydantic) into clean, compatible schemas suitable for MCP `inputSchema` and OpenAI `parameters`. It ensures that all internal references are resolved and that the resulting schema follows the strict requirements of AI tool-use protocols. - -MCP factories use the descriptor's runtime schema directly rather than this explicit -conversion utility. See the [factory input contract](mcp-server-factory.md#mcp-input-schema-contract) -for discovery semantics; the conversion APIs documented below remain available to -callers that explicitly request their transformations. +The Schema Converter normalizes module input and output schemas and can inline +local references for callers that request that transformation. The OpenAI +converter retains local references and definitions while normalizing input +schemas and applying strict mode when enabled. MCP discovery uses the +descriptor's runtime schema directly. See the +[factory input contract](mcp-server-factory.md#mcp-input-schema-contract). ## Scope @@ -44,7 +44,7 @@ callers that explicitly request their transformations. - **ModuleDescriptor** (apcore Registry) — Contains the raw `input_schema` and `output_schema` dicts. ### Outputs -- **JSON Schema Dict** (MCP/OpenAI Converters) — A self-contained, inlined schema dictionary. +- **JSON Schema Dict** — A normalized schema with local references inlined when requested. ### Dependencies - **apcore SDK (language-equivalent: apcore-python / apcore-js / apcore Rust crate)** — Provides the `ModuleDescriptor` structure and raw schema data. @@ -127,8 +127,7 @@ User-set `additionalProperties` values (whether `true`, `false`, or a subschema) ## Notes -- This component is critical for compatibility with MCP clients (like Claude Desktop) and OpenAI's API, which often struggle with unresolved JSON Schema references. -- It reuses patterns from apcore's internal `RefResolver` but is optimized for the specific constraints of tool-use protocols. +- Explicit inlining is available to consumers that require self-contained schemas. --- diff --git a/mcp/docs/srs-apcore-mcp.md b/mcp/docs/srs-apcore-mcp.md index 2e640bd8..0b128371 100644 --- a/mcp/docs/srs-apcore-mcp.md +++ b/mcp/docs/srs-apcore-mcp.md @@ -306,15 +306,13 @@ FR-SCHEMA-001 through FR-SCHEMA-003 describe the standalone SchemaConverter util | **Priority** | P0 | | **Traces to** | F-008 | -**Description:** The schema conversion for OpenAI `parameters` shall apply the same `$ref` inlining and `type: object` guarantee as the standalone SchemaConverter utility (FR-SCHEMA-001 through FR-SCHEMA-003). The resulting schema shall be usable as the `"parameters"` value in an OpenAI tool definition. +**Description** — The OpenAI tool converter shall normalize the input schema root and preserve local references with their definitions. It shall apply the strict schema transformation when strict mode is enabled. -**Input/Trigger:** A `ModuleDescriptor` with a populated `input_schema` dict. +**Input/Trigger** — A `ModuleDescriptor` with a populated `input_schema` dict. -**Expected Output:** An explicitly converted OpenAI parameters schema. OpenAI conversion may inline references and apply strict-mode rules; MCP factory discovery independently preserves the runtime schema and does not share that projection. +**Expected Output** — An OpenAI `parameters` schema with local references resolvable against its retained definitions. -**Boundary Conditions:** Same as FR-SCHEMA-001. - -**Error Conditions:** Same as FR-SCHEMA-001. +**Boundary Conditions** — An empty input schema produces an object schema with empty properties. --- diff --git a/mcp/docs/tech-design-apcore-mcp.md b/mcp/docs/tech-design-apcore-mcp.md index 4b7a39ec..7f627c75 100644 --- a/mcp/docs/tech-design-apcore-mcp.md +++ b/mcp/docs/tech-design-apcore-mcp.md @@ -310,13 +310,14 @@ graph TB #### ADR-04: Schema $ref Inlining for MCP/OpenAI Compatibility -**Context:** Pydantic's `model_json_schema()` may produce schemas with `$defs` and `$ref` references for nested models. Some MCP clients and OpenAI's function calling API may not support `$ref` resolution. +MCP discovery copies the descriptor's runtime input schema. OpenAI export +normalizes the root, retains local references and definitions, and applies +strict conversion when requested. Preserving the definitions keeps recursive +model references resolvable after projection. -**Decision:** Inline all `$ref` references before passing schemas to MCP or OpenAI, using apcore-python's `RefResolver` algorithm as reference but with a simpler self-contained inliner for `$defs`-local references. - -**Rationale:** Pydantic v2's `model_json_schema()` produces `$defs` at the root level with `$ref` pointers like `"$ref": "#/$defs/ModelName"`. These are local references that can be resolved by substitution. External file references (`apcore://` or relative paths) are not generated by Pydantic and are out of scope. - -**Consequences:** The `SchemaConverter` includes a `_inline_refs()` method that resolves all `$defs`-local `$ref` nodes. The `$defs` key is removed from the final schema. +The standalone `SchemaConverter` can inline local references for callers that +require inlined output. Successful inlining removes the definition table. +External references are outside the scope of that operation. #### ADR-05: Intentional Language-Idiomatic Differences Between Python and TypeScript @@ -740,9 +741,9 @@ src/apcore_mcp/ **File:** `src/apcore_mcp/adapters/schema.py` -**Responsibility:** Convert apcore `ModuleDescriptor.input_schema` and `output_schema` (JSON Schema dicts produced by Pydantic `model_json_schema()`) into clean schemas suitable for MCP `inputSchema` and OpenAI `parameters`. The primary task is `$defs`/`$ref` inlining and ensuring the root schema has `type: object`. - -MCPServerFactory discovery preserves the runtime input schema directly. This standalone converter is used only by callers explicitly requesting conversion and by OpenAI export paths. +**Responsibility** — Normalize apcore module schema roots and provide optional +local reference inlining. MCPServerFactory discovery copies the runtime input +schema. OpenAI export uses the normalized schema with local references retained. **Public API:** diff --git a/mcp/docs/test-plan-apcore-mcp.md b/mcp/docs/test-plan-apcore-mcp.md index a484438c..bc9f3111 100644 --- a/mcp/docs/test-plan-apcore-mcp.md +++ b/mcp/docs/test-plan-apcore-mcp.md @@ -2664,7 +2664,7 @@ public function by that name in any SDK. 3. Validate each dict against OpenAI tool schema structure. 4. Assert all module IDs are normalized (no dots). 5. Assert all parameters are valid JSON Schema. -- **Expected Result:** Output is valid OpenAI tools format. All $refs are inlined. All module IDs are normalized. +- **Expected Result** — Output uses the OpenAI tools format and normalized module IDs. The nested schema retains its local reference and the strict-converted definition it resolves to. - **Traceability:** F-008 --- diff --git a/mcp/python/tests/integration/test_integration.py b/mcp/python/tests/integration/test_integration.py index 0baacd3d..d2c3fd35 100644 --- a/mcp/python/tests/integration/test_integration.py +++ b/mcp/python/tests/integration/test_integration.py @@ -11,6 +11,7 @@ from typing import Any import pytest +from jsonschema import Draft202012Validator from mcp import types as mcp_types from apcore_mcp import to_openai_tools @@ -417,21 +418,18 @@ def test_parameters_are_valid_json_schema(self, registry: StubRegistry) -> None: assert isinstance(params, dict) assert params.get("type") == "object", f"Parameters for {tool['function']['name']} missing type: object" - def test_nested_ref_schema_is_inlined(self, registry: StubRegistry) -> None: - """The $ref in the nested schema is resolved and inlined, $defs removed.""" + def test_nested_ref_schema_is_preserved_and_hardened(self, registry: StubRegistry) -> None: + """Strict conversion keeps the local reference and transforms its definition.""" tools = to_openai_tools(registry) workflow_tool = next(t for t in tools if t["function"]["name"] == "workflow-run") params = workflow_tool["function"]["parameters"] - # $defs should be removed - assert "$defs" not in params + assert params["properties"]["steps"]["items"]["$ref"] == "#/$defs/Step" + assert params["$defs"]["Step"]["additionalProperties"] is False - # The steps array items should have the inlined Step schema - steps_schema = params["properties"]["steps"] - assert steps_schema["type"] == "array" - items = steps_schema["items"] - assert items["type"] == "object" - assert "name" in items["properties"] + validator = Draft202012Validator(params) + assert validator.is_valid({"steps": [{"name": "start", "params": None}]}) + assert not validator.is_valid({"steps": [{"name": "start"}]}) def test_empty_schema_gets_default(self, registry: StubRegistry) -> None: """Empty input_schema is converted to a normalized object schema.