Skip to content

feat(adapter): add bridge_adapter Python SDK + TypeScript MemoryAdapter interface#339

Open
gugu23456789 wants to merge 119 commits into
TencentCloud:mainfrom
gugu23456789:bridge-adapter
Open

feat(adapter): add bridge_adapter Python SDK + TypeScript MemoryAdapter interface#339
gugu23456789 wants to merge 119 commits into
TencentCloud:mainfrom
gugu23456789:bridge-adapter

Conversation

@gugu23456789

@gugu23456789 gugu23456789 commented Jul 1, 2026

Copy link
Copy Markdown

Summary

One engine, three entry points this PR implements a unified access layer for TDAI Memory Gateway v2:

Entry Point Implementation Use Case
Python SDK TdaiAdapter ABC + BridgeAdapter Python-native agent frameworks
TypeScript SDK MemoryAdapter interface + BaseMemoryAdapter + TdaiHttpClient TypeScript agent frameworks
MCP stdio JSON-RPC 2.0 server (5 tools, 5 defense gates) Any MCP-compliant agent platform

All three share the same abstract contract (recall/capture/search) and the same backend (TDAI Gateway). The MCP layer also serves as the integration point for platforms that don't have a native SDK Codex CLI, Claude Code, CodeBuddy, Trae IDE, Cursor, etc. connect with a single line of config.

With MCP gaining traction as an open standard for agent-tool interaction, this PR positions TDAI to be natively accessible from any MCP-compliant platform without per-platform adapter code.

Configuration: Local vs Multi-Tenant

All three entry points share the same TDAI_* environment variables.
Set them once; all three consume them.

Path A: Local Mode (Zero Config)

# Start the MCP server with defaults:
#   endpoint: http://127.0.0.1:8420
#   api key:  empty (loopback, no auth required)
#   service:  mem-rkgqhd5z (single shared DB)
python -m bridge.mcp.server
# Python SDK - same defaults
from bridge_adapter import TdaiAdapterRegistry
adapter = TdaiAdapterRegistry.create("bridge")
// TypeScript SDK - same defaults
import { TdaiHttpClient } from "./tdai-http-client";
const client = new TdaiHttpClient();

Path B: Multi-Tenant Mode (Per-Project Isolation)

# Each project gets its own SQLite database on the same Gateway
TDAI_SERVICE_ID=repo-spz-gatekeeper python -m bridge.mcp.server
TDAI_SERVICE_ID=repo-bridge-core    python -m bridge.mcp.server
TDAI_SERVICE_ID=repo-zthl-research  python -m bridge.mcp.server
# Python SDK - explicit service_id
cfg = TdaiConfig.from_env()  # reads TDAI_SERVICE_ID
adapter = BridgeAdapter(config=cfg)
// TypeScript SDK - explicit service_id
const client = new TdaiHttpClient({ serviceId: "my-project" });

Path C: Remote Gateway (Cloud)

TDAI_ENDPOINT=https://cloud.example.com:8420 \
TDAI_API_KEY=sk-your-key \
TDAI_SERVICE_ID=my-project \
python -m bridge.mcp.server

API Key Resolution

The MCP server resolves keys in this order:

  1. MCP_BRIDGE_API_KEY (MCP-specific override)
  2. TDAI_API_KEY (shared SDK key)
  3. Empty string -> loopback mode (local only)

Tested by test_config.py (7 tests) and test_dual_path.py (4 tests).

Python SDK

from bridge_adapter import TdaiAdapterRegistry
adapter = TdaiAdapterRegistry.create("bridge")
ctx = await adapter.recall("user preferences")

TypeScript SDK

import { TdaiHttpClient } from "./tdai-http-client";
const client = new TdaiHttpClient({ apiKey: process.env.TDAI_API_KEY });
const health = await client.health();

MCP stdio (any MCP-compliant client)

# ~/.codex/config.toml
[mcp_servers.tdai_memory]
command = "python"
args = ["-m", "bridge.mcp.server"]

Then the agent calls tdai_recall, tdai_capture, etc. as native MCP tools.

Deliverables

Python SDK (bridge_adapter/)

Component Location
TdaiAdapter ABC abstract base class with retry, middleware, recall cache, graceful degradation bridge_adapter/base.py
BridgeAdapter httpx Gateway (7 endpoints, retry, structured errors) bridge_adapter/client.py
UnifiedErr 7 typed error classes, exponential backoff retry bridge_adapter/errors.py
TdaiMiddleware system before/after/onError hooks, metrics bridge_adapter/base.py
TdaiAdapterRegistry create("bridge" or "hermes_v2"), list() bridge_adapter/__init__.py
BufferedAdapter dedup + compaction wrapper bridge_adapter/buffered.py
HermesV2Adapter hermes-v2 chat-completion proxy bridge_adapter/hermes_v2.py
Config loader JSON/TOML/env chain bridge_adapter/config.py

TypeScript SDK (src/core/)

Component Location
MemoryAdapter interface src/core/types.ts
BaseMemoryAdapter retry + middleware + recall cache + graceful degradation src/core/base-memory-adapter.ts
TdaiHttpClient 8 Gateway endpoints, 7 typed errors, env-var defaults src/core/tdai-http-client.ts
Tests src/core/memory-adapter.test.ts (19) + src/core/tdai-http-client.test.ts (10)

MCP stdio Transport Layer (bridge/mcp/)

Component Location
MCP stdio server 5 tools, pure JSON-RPC 2.0, zero framework dep bridge/mcp/server.py
5-layer defense gates G0 JSON-RPC G1 API Key G2 rate-limit G3 circuit breaker G4 audit bridge/mcp/server.py
Graceful fallback server.py bridge/mcp_health.py (1 tool, 4 gates, independent process) bridge/mcp_health.py
TS MCP client StdioClientTransport, inherits server-side gates bridge/mcp/tdai-memory-client.ts
Tests protocol compliance: 14 + red-team: 13 bridge/mcp/tests/test_protocol.py + test_redteam.py

Test Summary

Suite Location Count
MCP protocol compliance bridge/mcp/tests/test_protocol.py 14
MCP red-team bridge/mcp/tests/test_redteam.py 13
TS MemoryAdapter src/core/memory-adapter.test.ts 19
TS TdaiHttpClient src/core/tdai-http-client.test.ts 10
PR-submitted total 63

Documentation

File Contents
bridge/mcp/INTEGRATION.md Multi-platform MCP config + fallback chain
bridge/mcp/REDTEAM_FINDINGS.md Red-team assessment (paper-supplement style)
docs/tdai-adapter-architecture.md SDK architecture + cross-language design
docs/platform-adapter-comparison.md 5-column adapter matrix including this PR

Key Design Decisions

  1. ABC over concrete Subclasses implement only 4 _impl methods; the base class provides retry, middleware, caching, and graceful degradation for free.
  2. MCP over per-platform adapters One stdio server replaces N platform-specific adapters. Any MCP client connects with one config line.
  3. Defense gates always active G0G4 run on every request regardless of transport.
  4. Zero MCP framework dependency Pure JSON-RPC 2.0, no supply-chain risk from SDK deps.
  5. Graceful degradation at every layer MCP fallback SDK safe defaults return.
  6. Dual-language parity Python ABC and TypeScript interface+client share equivalent abstractions and error semantics.

CI Verification

Evidence: https://github.com/gugu23456789/tdai-adapter-evidence (test logs, PR data, commit history)

Closes #235


Progress

  • Python SDK (bridge_adapter) — TdaiAdapter ABC + HermesV2Adapter + BridgeAdapter
  • TypeScript SDK — TdaiAdapter interface + tdai-http-client
  • MCP stdio server with defense gates (G0-G4)
  • Dual-path config (local mode + multi-tenant mode)
  • CI encoding defense — 5-layer mojibake prevention (L1+L5)
  • Cross-language SDK parity (Python ABC <-> TS interface)
  • SHA256 integrity verification + CI gate
  • Node 24 upgrade (was 22)
  • Awaiting upstream review

CI Status (final)

Latest: 860f225e — 8/8 jobs passing

Job Status
Install OK
Test TS (29) OK
Test Python (import + SHA256) OK
Encoding Defense (L1+L5) OK
Manifest OK
Pack OK
Size Guard OK
8/8

Full CI history in comment below.

@gugu23456789

gugu23456789 commented Jul 3, 2026

Copy link
Copy Markdown
Author

CI Status (final)

Latest: 860f225e — 8/8 jobs passing

Job Status
Install OK
Test TS (29) OK
Test Python (import + SHA256) OK
Encoding Defense (L1+L5) OK
Manifest OK
Pack OK
Size Guard OK
8/8

Phase Summary

Phase 1: SDK push (env-var fallback, dual-path)
Phase 2: Test infra (dual-path tests, Node 22->24)
Phase 3: Documentation & evidence
Phase 4: Mojibake crisis (5-layer encoding defense)
Phase 5: Stabilization (8/8 green)

Evidence

github-actions added 19 commits July 4, 2026 09:01
G1: RateLimitGate (sliding window + self-fallback) - G2: CircuitBreakerGate (closed-open + cooldown escalation) - G3: AuditGate (ring buffer + ConsoleExporter + sampling 1/10) - 11 tests with mocked time - Wired into BaseMemoryAdapter - package-lock.json tracked, npm ci, npm audit - OpenSSF Scorecard CI job, Dependabot weekly scan
3 vulnerabilities patched in server.py + mcp_health.py: - Rate limiter self-fallback (3 fails -> 30s fail-open) - CB cooldown escalation (double on rapid cycles, max 300s) - Audit ring buffer (1024 max) + sampling (1/10) Also fixed pre-existing missing def _check_api_key() in mcp_health.py
rainforest888 added a commit to rainforest888/TencentDB-Agent-Memory that referenced this pull request Jul 4, 2026
rainforest888 added a commit to rainforest888/TencentDB-Agent-Memory that referenced this pull request Jul 4, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Cross-Platform Adapters for the Memory Plugin

2 participants