corpusos

MCP数据服务

提供方 Corpus-OS · 包名 corpusos

数据服务 stdio · 本地进程 未标注 社区 / 第三方 Claude DesktopCursorClineClaude Code
查看接入方式

Open-source protocol suite standardizing LLM, Vector, Graph, and Embedding infrastructure across LangChain, LlamaIndex, AutoGen, CrewAI, Semantic Kern

一句话选型结论

按资料字段整理

corpusos 属于数据服务类 MCP 服务器,stdio · 本地进程,鉴权方式未标注,可直接接入 Claude Desktop、Cursor、Cline 等,有可直接执行的安装命令。接入前先确认权限范围;涉及写入、删除或付款的操作,建议先在测试环境验证。

分类数据服务 传输方式stdio · 本地进程 鉴权未标注 部署方式本地部署
GitHub 星标 258 仓库热度,无公开仓库时显示未标注
工具数 未标注 暴露给模型的工具数量
资源 / 提示词 0 / 0 资源与提示词模板数量
维护方 社区 / 第三方 核验等级 仅资料核对

工具与能力

数据服务
数量来自来源目录的标注,具体工具清单以官方文档为准
工具数量未标注暴露给模型可调用的工具个数
资源数量0可读取的资源条目
提示词数量0内置提示词模板数量

能力标签

corpusos agents ai-agents ai-infrastructure anthropic

支持客户端

适用场景

corpusosagentsai-agents

安装与配置

stdio · 本地进程 未标注
客户端在本机拉起子进程,数据不出本机
pip install corpusos

这条命令只是入口,具体启动参数请按官方文档补齐,不要直接照搬到别的服务器。

  1. 1
    准备运行环境

    stdio 服务在本地起进程,需要先装好 Cross-platform,再按安装命令拉取依赖。

  2. 2
    安装服务

    复制上面的安装命令执行;命令里带占位符的位置,换成自己的密钥或路径。

  3. 3
    写入客户端配置

    在客户端的 MCP 配置里填好启动命令和参数,保存后完全退出客户端再打开,让新配置生效。

  4. 4
    验证是否可用

    连接成功后随便调一个只读工具,确认能返回结果,再接入正式流程。

典型使用场景

3 类
按分类与标签整理的常见用法,具体以官方文档为准
数据库查询

用自然语言查库、取数,不用手写 SQL。

数据同步与清洗

把多来源数据拉到一处做整理。

报表取数

按口径快速拉出统计结果。

选择建议

选之前先看这几条
按条目字段给出的判断,不替你决定用不用

值得选的地方

  • 有现成的安装命令,不用自己找入口,照着跑就能起服务。
  • 已适配 Claude Desktop、Cursor、Cline,换客户端不用重新研究配置。

先想清楚的地方

  • stdio 方式要求本地装好运行时(如 Node.js),换机器要重新装一遍。
  • 资料没标注工具数量,实际能力要装好后确认。
  • 版本更新与行为细节以官方仓库为准。

更适合

  • 需要在数据服务场景里让模型直接调用外部能力的人。
  • 已经在用 Claude Desktop、Cursor 的用户,接入路径最短。
  • 想先快速试一下、能接受在本地或自有环境跑服务的人。

不太适合

  • 完全不想在本地装环境的人。
  • 需要厂商级 SLA 和技术支持的生产环境。

同类对比

6 个同类
同分类里挑最接近的几条,字段以各自详情页为准
MCP 服务器工具数传输方式部署方式安装命令最后核验
corpusos当前 未标注 stdio · 本地进程 本地部署 有 2026-04-08
Memory 9d25f64e 9 未标注 未标注 无 2026-05-17
Getzep MCP 9 stdio · 本地进程 本地部署 有 2026-05-17
anything-llm 未标注 stdio · 本地进程 本地部署 有 2026-04-11
Prisma MCP Server 未标注 stdio · 本地进程 本地部署 有 2026-05-17
Astr Bot 未标注 stdio · 本地进程 本地部署 有 2026-05-17

服务器档案

数据服务
字段来自项目仓库与公开索引,中文说明由本站标注
提供方Corpus-OS上游标注的维护方 Corpus-OS
分类数据服务本站按上游分类展示
连接方式stdio · 本地进程客户端在本机拉起子进程,数据不出本机
鉴权方式未标注远程服务建议用最小权限凭据
维护方社区 / 第三方核验等级 仅资料核对
包名 / 运行时corpusos · Cross-platform本地安装时用到的包标识与运行时
部署类型本地部署上游给出的部署形态
最近核验2026-04-08上游最后核验时间

详细介绍

41.9 KB
来自项目仓库与上游目录的原文,未做删改

Corpus OS

Reference implementation of the Corpus OS — a wire-first, vendor-neutral SDK for interoperable AI frameworks and data backends across four domains: LLM, Embedding, Vector, and Graph.


Contact: team@corpusos.com
Website: https://corpusos.com
Docs: https://docs.corpusos.com

---```
┌──────────────────────────────────────────────────────────────────────┐
│ Your App / Agents / RAG Pipelines │
│ (LangChain · LlamaIndex · Semantic Kernel · CrewAI · AutoGen · MCP) │
├──────────────────────────────────────────────────────────────────────┤
│ Corpus OS Protocol and SDK. │
│ One protocol · One error taxonomy · One metrics model │
├──────────┬──────────────┬────────────┬───────────────────────────────┤
│ LLM/v1 │ Embedding/v1 │ Vector/v1 │ Graph/v1 │
├──────────┴──────────────┴────────────┴───────────────────────────────┤
│ Any Provider: OpenAI · Anthropic · Pinecone · Neo4j · ... │
└──────────────────────────────────────────────────────────────────────┘


**Keep your frameworks. Standardize your infrastructure.**

> **Open-Core Model**: The **Corpus OS** Protocol Suite and SDK are **fully open source** (Apache-2.0). Corpus Router and official production adapters are **commercial**, optional, and built on the same public protocols. Using this SDK does **not** lock you into CORPUS Router.

---

## Table of Contents

1. Why CORPUS
2. How CORPUS Compares
3. When Not to Use CORPUS
4. Install
5. Quick Start
6. Domain Examples
7. Core Concepts
8. Error Taxonomy & Observability
9. Performance & Configuration
10. Testing & Conformance
11. Documentation Layout
12. FAQ
13. Contributing
14. License & Commercial Options

---

## Why Corpus OS

Modern AI platforms juggle multiple LLM, embedding, vector, and graph backends. Each vendor ships unique APIs, error schemes, rate limits, and capabilities — making cross-provider integration brittle and costly.

**The problem:**

- **Provider proliferation** — Dozens of incompatible APIs across AI infrastructure
- **Duplicate integration** — Different error handling, observability, and resilience patterns rewritten per provider and framework
- **Vendor lock-in** — Applications tightly coupled to specific backend choices
- **Operational complexity** — Inconsistent monitoring and debugging across services

**Corpus OS provides:**

- **Stable, runtime-checkable protocols** across all four domains
- **Normalized errors** with retry hints and machine-actionable scopes
- **SIEM-safe metrics** (low-cardinality, tenant-hashed, no PII)
- **Deadline propagation** for cancellation and cost control
- **Two modes** — compose under your own router (`thin`) or use lightweight built-in infra (`standalone`)
- **Wire-first design** — canonical JSON envelopes implementable in any language, with this SDK as reference

Corpus OS is **not** a replacement for LangChain, LlamaIndex, Semantic Kernel, CrewAI, AutoGen, or MCP. Use those for agent-specific orchestration, agents, tools, and RAG pipelines. Use Corpus OS to standardize the **infrastructure layer underneath them**. Your app teams keep their frameworks. Your platform team gets one protocol, one error taxonomy, and one observability model across everything.

---

## How Corpus OS Compares

| Aspect | LangChain / LlamaIndex | OpenRouter | MCP | **Corpus OS** |
|---|---|---|---|---|
| **Scope** | Application framework | LLM unification | Tools & data sources | **AI infrastructure protocols** |
| **Domains** | LLM + Tools | LLM only | Tools + Data | **LLM + Vector + Graph + Embedding** |
| **Error Standardization** | Partial | Limited | N/A | **Comprehensive taxonomy** |
| **Multi-Provider Routing** | Basic | Managed service | N/A | **Protocol for any router** |
| **Observability** | Basic | Limited | N/A | **Built-in metrics + tracing** |
| **Vendor Neutrality** | High | Service-dependent | High | **Protocol-first, no lock-in** |

### Who is this for?

- **App developers** — Keep using your framework of choice. Talk to all backends through Corpus OS protocols. Swap providers or frameworks without rewriting integration code.
- **Framework maintainers** — Implement one CORPUS adapter per protocol. Instantly support any conformant backend.
- **Backend vendors** — Implement `llm/v1`, `embedding/v1`, `vector/v1`, or `graph/v1` once, run the conformance suite, and your service works with every framework.
- **Platform / infra teams** — Unified observability: normalized error codes, deadlines, and metrics. One set of dashboards and SLOs across all AI traffic.
- **MCP users** — The Corpus OS MCP server exposes protocols as standard MCP tools. Any MCP client can call into your infra with consistent behavior.

### Integration Patterns

| Pattern | How It Works | What You Get |
|---|---|---|
| Framework → Corpus OS → Providers | Framework uses Corpus OS as client | Unified errors/metrics across providers |
| Corpus OS → Framework-as-adapter → Providers | Framework wrapped as Corpus OS adapter | Reuse existing chains/indices as "providers" |
| Mixed | Both of the above | Gradual migration, no big-bang rewrites |

Large teams typically run all three patterns at once.

---

## When Not to Use CORPUS

You probably don't need Corpus OS if:

- **Single-provider and happy** — One backend, fine with their SDK and breaking changes.
- **No governance pressure** — No per-tenant isolation, budgets, audit trails, or data residency.
- **No cross-domain orchestration** — Not coordinating LLM + Vector + Graph + Embedding together.
- **Quick throwaway prototype** — Lock-in, metrics, and resilience aren't worth thinking about yet.

If any of these stop being true, `corpus_sdk` is the incremental next step.

---

## Install```bash
pip install corpus_sdk

Python ≥ 3.10 recommended. No heavy runtime dependencies.


⚡ Quick Start```python

import asyncio
from corpus_sdk.llm.llm_base import (
BaseLLMAdapter, OperationContext, LLMCompletion,
LLMCapabilities, TokenUsage
)

class QuickAdapter(BaseLLMAdapter):
async def _do_capabilities(self) -> LLMCapabilities:
return LLMCapabilities(
server="quick-demo",
version="1.0.0",
model_family="demo",
max_context_length=4096,
)

async def _do_complete(self, messages, model=None, **kwargs) -> LLMCompletion:
    return LLMCompletion(
        text="Hello from CORPUS!",
        model=model or "quick-demo",
        model_family="demo",
        usage=TokenUsage(prompt_tokens=2, completion_tokens=3, total_tokens=5),
        finish_reason="stop",
    )

async def _do_count_tokens(self, text, *, model=None, ctx=None) -> int:
    return len(text.split())  # Simple word count

async def _do_health(self, *, ctx=None) -> dict:
    return {"ok": True, "server": "quick-demo"}

Usage

async def main():
print("=" * 80)
print("Quick LLM Adapter Demo")
print("=" * 80)

adapter = QuickAdapter()
ctx = OperationContext(request_id="test-123")

# Test 1: Capabilities
caps = await adapter.capabilities()
print(f"\n✅ Capabilities:")
print(f"   Server: {caps.server} v{caps.version}")
print(f"   Model family: {caps.model_family}")
print(f"   Max context: {caps.max_context_length}")

# Test 2: Completion
result = await adapter.complete(
    messages=[{"role": "user", "content": "Hi"}],
    ctx=ctx
)
print(f"\n✅ Completion:")
print(f"   Response: {result.text}")
print(f"   Model: {result.model}")
print(f"   Tokens used: {result.usage.total_tokens} (prompt: {result.usage.prompt_tokens}, completion: {result.usage.completion_tokens})")
print(f"   Finish reason: {result.finish_reason}")

# Test 3: Token counting
tokens = await adapter.count_tokens("This is a test message")
print(f"\n✅ Token Counting:")
print(f"   Text: 'This is a test message'")
print(f"   Tokens: {tokens}")

# Test 4: Health check
health = await adapter.health()
print(f"\n✅ Health Check:")
print(f"   OK: {health.get('ok', False)}")
print(f"   Server: {health.get('server', 'unknown')}")

print("\n" + "=" * 80)
print("✅ All tests passed!")
print("=" * 80)

if name == "main":
asyncio.run(main())


A complete quick start with all four protocols is in `docs/guides/QUICK_START.md`.

---

## Domain Examples

> **Minimal viable adapter:** Implement `_do_capabilities`, your core operation (`_do_embed`, `_do_complete`, `_do_query`, etc.), and `_do_health`. All other methods have safe no-op defaults — you only override what you need.

> In all examples, swap `Example*Adapter` with your actual adapter class that inherits the corresponding base and implements `_do_*` hooks.

Embeddings```python
import asyncio
from corpus_sdk.embedding.embedding_base import (
    BaseEmbeddingAdapter, EmbedSpec, OperationContext,
    EmbeddingVector, EmbeddingCapabilities, EmbedResult
)

class QuickEmbeddingAdapter(BaseEmbeddingAdapter):
    async def _do_capabilities(self) -> EmbeddingCapabilities:
        return EmbeddingCapabilities(
            server="quick-embeddings",
            version="1.0.0",
            supported_models=("quick-embed-001",),
            max_batch_size=128,
            max_text_length=8192,
            supports_normalization=True,
            normalizes_at_source=False,
            supports_deadline=True,
            supports_token_counting=False,
        )

    async def _do_embed(self, spec: EmbedSpec, *, ctx=None) -> EmbedResult:
        vec = [0.1, 0.2, 0.3]
        return EmbedResult(
            embedding=EmbeddingVector(
                vector=vec,
                text=spec.text,
                model=spec.model,
                dimensions=len(vec)
            ),
            model=spec.model,
            text=spec.text,
            tokens_used=None,
            truncated=False,
        )

    async def _do_health(self, *, ctx=None) -> dict:
        return {"ok": True, "server": "quick-embeddings", "version": "1.0.0"}

# Usage
async def main():
    print("=" * 80)
    print("Quick Embedding Adapter Demo")
    print("=" * 80)

    async with QuickEmbeddingAdapter() as adapter:
        ctx = OperationContext(request_id="req-1", tenant="acme")

        # Test 1: Capabilities
        caps = await adapter.capabilities()
        print(f"\n✅ Capabilities:")
        print(f"   Server: {caps.server} v{caps.version}")
        print(f"   Supported models: {caps.supported_models}")
        print(f"   Max batch size: {caps.max_batch_size}")
        print(f"   Max text length: {caps.max_text_length}")
        print(f"   Supports normalization: {caps.supports_normalization}")
        print(f"   Supports deadline: {caps.supports_deadline}")

        # Test 2: Embedding
        res = await adapter.embed(
            EmbedSpec(text="hello world", model="quick-embed-001"), ctx=ctx
        )
        print(f"\n✅ Embedding:")
        print(f"   Text: '{res.text}'")
        print(f"   Vector: {res.embedding.vector}")
        print(f"   Dimensions: {res.embedding.dimensions}")
        print(f"   Model: {res.model}")
        print(f"   Truncated: {res.truncated}")

        # Test 3: Multiple embeddings
        texts = ["first text", "second text", "third text"]
        print(f"\n✅ Multiple Embeddings:")
        for i, text in enumerate(texts, 1):
            res = await adapter.embed(
                EmbedSpec(text=text, model="quick-embed-001"), ctx=ctx
            )
            print(f"   {i}. '{text}' → {res.embedding.dimensions}D vector")

        # Test 4: Health check
        health = await adapter.health()
        print(f"\n✅ Health Check:")
        print(f"   OK: {health.get('ok', False)}")
        print(f"   Server: {health.get('server', 'unknown')} v{health.get('version', 'unknown')}")

        print("\n" + "=" * 80)
        print("✅ All tests passed!")
        print("=" * 80)

if __name__ == "__main__":
    asyncio.run(main())

LLM```python
import asyncio
from corpus_sdk.llm.llm_base import (
BaseLLMAdapter, OperationContext, LLMCompletion,
TokenUsage, LLMCapabilities
)

class QuickLLMAdapter(BaseLLMAdapter):
async def _do_capabilities(self) -> LLMCapabilities:
return LLMCapabilities(
server="quick-llm",
version="1.0.0",
model_family="gpt-4",
max_context_length=8192,
supports_streaming=True,
supports_roles=True,
supports_json_output=False,
supports_parallel_tool_calls=False,
idempotent_writes=False,
supports_multi_tenant=True,
supports_system_message=True,
)

async def _do_complete(self, messages, model, **kwargs) -> LLMCompletion:
    return LLMCompletion(
        text="Hello from quick-llm!",
        model=model,
        model_family="gpt-4",
        usage=TokenUsage(prompt_tokens=5, completion_tokens=5, total_tokens=10),
        finish_reason="stop",
    )

async def _do_count_tokens(self, text, *, model=None, ctx=None) -> int:
    return len(text.split())  # Simple word count

async def _do_health(self, *, ctx=None) -> dict:
    return {"ok": True, "server": "quick-llm", "version": "1.0.0"}

Usage

async def main():
print("=" * 80)
print("Quick LLM Adapter Demo")
print("=" * 80)

async with QuickLLMAdapter() as adapter:
    ctx = OperationContext(request_id="req-2", tenant="acme")

    # Test 1: Capabilities
    caps = await adapter.capabilities()
    print(f"\n✅ Capabilities:")
    print(f"   Server: {caps.server} v{caps.version}")
    print(f"   Model family: {caps.model_family}")
    print(f"   Max context length: {caps.max_context_length}")
    print(f"   Supports streaming: {caps.supports_streaming}")
    print(f"   Supports roles: {caps.supports_roles}")
    print(f"   Supports system message: {caps.supports_system_message}")
    print(f"   Supports multi-tenant: {caps.supports_multi_tenant}")

    # Test 2: Completion
    resp = await adapter.complete(
        messages=[{"role": "user", "content": "Say hi"}],
        model="quick-llm-001",
        ctx=ctx,
    )
    print(f"\n✅ Completion:")
    print(f"   Response: {resp.text}")
    print(f"   Model: {resp.model}")
    print(f"   Model family: {resp.model_family}")
    print(f"   Tokens: {resp.usage.total_tokens} (prompt: {resp.usage.prompt_tokens}, completion: {resp.usage.completion_tokens})")
    print(f"   Finish reason: {resp.finish_reason}")

    # Test 3: Multi-message conversation
    messages = [
        {"role": "system", "content": "You are a helpful assistant"},
        {"role": "user", "content": "Hello"},
        {"role": "assistant", "content": "Hi there!"},
        {"role": "user", "content": "How are you?"}
    ]
    resp = await adapter.complete(messages=messages, model="quick-llm-001", ctx=ctx)
    print(f"\n✅ Multi-turn Conversation:")
    print(f"   Messages: {len(messages)} turns")
    print(f"   Response: {resp.text}")

    # Test 4: Token counting
    test_text = "This is a longer text to count tokens for testing purposes"
    tokens = await adapter.count_tokens(test_text, model="quick-llm-001")
    print(f"\n✅ Token Counting:")
    print(f"   Text: '{test_text}'")
    print(f"   Tokens: {tokens}")

    # Test 5: Health check
    health = await adapter.health()
    print(f"\n✅ Health Check:")
    print(f"   OK: {health.get('ok', False)}")
    print(f"   Server: {health.get('server', 'unknown')} v{health.get('version', 'unknown')}")

    print("\n" + "=" * 80)
    print("✅ All tests passed!")
    print("=" * 80)

if name == "main":
asyncio.run(main())


Vector```python

import asyncio
from corpus_sdk.vector.vector_base import (
    BaseVectorAdapter, VectorCapabilities, QuerySpec, UpsertSpec, UpsertResult,
    QueryResult, Vector, VectorMatch, OperationContext, VectorID
)

class QuickVectorAdapter(BaseVectorAdapter):
    def __init__(self):
        super().__init__()
        # Simple in-memory storage
        self.vectors = {}

    async def _do_capabilities(self) -> VectorCapabilities:
        return VectorCapabilities(
            server="quick-vector",
            version="1.0.0",
            max_dimensions=3
        )

    async def _do_upsert(self, spec: UpsertSpec, *, ctx=None) -> UpsertResult:
        """Store vectors in memory"""
        ns = spec.namespace or "default"
        if ns not in self.vectors:
            self.vectors[ns] = []
        self.vectors[ns].extend(spec.vectors)

        return UpsertResult(
            upserted_count=len(spec.vectors),
            failed_count=0,
            failures=[]
        )

    async def _do_query(self, spec: QuerySpec, *, ctx=None) -> QueryResult:
        """Search for similar vectors"""
        ns = spec.namespace or "default"
        stored_vectors = self.vectors.get(ns, [])

        # Simple cosine similarity
        def cosine_sim(a, b):
            dot = sum(x * y for x, y in zip(a, b))
            mag_a = sum(x * x for x in a) ** 0.5
            mag_b = sum(x * x for x in b) ** 0.5
            return dot / (mag_a * mag_b) if mag_a and mag_b else 0

        matches = []
        for vec in stored_vectors:
            score = cosine_sim(spec.vector, vec.vector)
            matches.append(VectorMatch(vector=vec, score=score, distance=1-score))

        # Sort by score descending
        matches.sort(key=lambda m: m.score, reverse=True)
        top_matches = matches[:spec.top_k] if spec.top_k else matches

        return QueryResult(
            matches=top_matches,
            query_vector=spec.vector,
            namespace=ns,
            total_matches=len(top_matches),
        )

    async def _do_health(self, *, ctx=None) -> dict:
        return {"ok": True, "server": "quick-vector", "version": "1.0.0"}

# Usage - Complete flow
async def main():
    print("=" * 80)
    print("Quick Vector Adapter Demo")
    print("=" * 80)

    adapter = QuickVectorAdapter()
    ctx = OperationContext(request_id="req-3", tenant="acme")

    # Test 1: Capabilities
    caps = await adapter.capabilities()
    print(f"\n✅ Capabilities:")
    print(f"   Server: {caps.server} v{caps.version}")
    print(f"   Max dimensions: {caps.max_dimensions}")

    # Test 2: Upsert vectors
    vectors_to_add = [
        Vector(id=VectorID("v1"), vector=[0.1, 0.2, 0.3], metadata={"label": "first"}),
        Vector(id=VectorID("v2"), vector=[0.4, 0.5, 0.6], metadata={"label": "second"}),
        Vector(id=VectorID("v3"), vector=[0.7, 0.8, 0.9], metadata={"label": "third"}),
    ]

    upsert_result = await adapter.upsert(
        UpsertSpec(vectors=vectors_to_add),
        ctx=ctx
    )
    print(f"\n✅ Upsert:")
    print(f"   Upserted: {upsert_result.upserted_count} vectors")
    print(f"   Failed: {upsert_result.failed_count} vectors")

    # Test 3: Query for similar vectors (top_k=2 REQUIRED by SDK)
    query_result = await adapter.query(
        QuerySpec(vector=[0.1, 0.2, 0.3], top_k=2),
        ctx=ctx
    )
    print(f"\n✅ Query (top 2):")
    print(f"   Query vector: {query_result.query_vector}")
    print(f"   Total matches: {query_result.total_matches}")
    print(f"   Results:")
    for i, match in enumerate(query_result.matches, 1):
        print(f"      {i}. ID: {match.vector.id}, Score: {match.score:.3f}, Distance: {match.distance:.3f}")
        print(f"         Metadata: {match.vector.metadata}")

    # Test 4: Query all vectors (with top_k=10)
    query_result_all = await adapter.query(
        QuerySpec(vector=[0.5, 0.5, 0.5], top_k=10),
        ctx=ctx
    )
    print(f"\n✅ Query (all matches):")
    print(f"   Query vector: [0.5, 0.5, 0.5]")
    print(f"   Total matches: {query_result_all.total_matches}")
    for i, match in enumerate(query_result_all.matches, 1):
        print(f"      {i}. ID: {match.vector.id}, Score: {match.score:.3f}")

    # Test 5: Namespace support
    ns_vectors = [
        Vector(id=VectorID("ns1"), vector=[0.9, 0.8, 0.7], metadata={"type": "namespace_test"}),
    ]
    upsert_ns = await adapter.upsert(
        UpsertSpec(vectors=ns_vectors, namespace="test-namespace"),
        ctx=ctx
    )
    print(f"\n✅ Namespace Support:")
    print(f"   Upserted {upsert_ns.upserted_count} vector(s) to 'test-namespace'")

    query_ns = await adapter.query(
        QuerySpec(vector=[0.9, 0.8, 0.7], top_k=5, namespace="test-namespace"),
        ctx=ctx
    )
    print(f"   Query in 'test-namespace': {query_ns.total_matches} match(es)")

    # Test 6: Health check
    health = await adapter.health()
    print(f"\n✅ Health Check:")
    print(f"   OK: {health.get('ok', False)}")
    print(f"   Server: {health.get('server', 'unknown')} v{health.get('version', 'unknown')}")

    print("\n" + "=" * 80)
    print("✅ All tests passed!")
    print("=" * 80)

if __name__ == "__main__":
    asyncio.run(main())

Graph```python
import asyncio
from corpus_sdk.graph.graph_base import (
BaseGraphAdapter, GraphCapabilities, UpsertNodesSpec,
Node, GraphID, OperationContext, GraphQuerySpec, QueryResult
)

class QuickGraphAdapter(BaseGraphAdapter):
def init(self):
super().init()
# Simple in-memory storage
self.nodes = {}

async def _do_capabilities(self) -> GraphCapabilities:
    return GraphCapabilities(
        server="quick-graph",
        version="1.0.0",
        supported_query_dialects=("cypher",),
        supports_stream_query=True,
        supports_bulk_vertices=True,
        supports_batch=True,
        supports_schema=True,
    )

async def _do_upsert_nodes(self, spec: UpsertNodesSpec, *, ctx=None):
    # Store nodes in memory
    for node in spec.nodes:
        self.nodes[str(node.id)] = node

    from corpus_sdk.graph.graph_base import UpsertResult
    return UpsertResult(
        upserted_count=len(spec.nodes),
        failed_count=0,
        failures=[]
    )

async def _do_query(self, spec: GraphQuerySpec, *, ctx=None) -> QueryResult:
    return QueryResult(
        records=[{"id": 1, "name": "Ada"}],
        summary={"rows": 1},
        dialect=spec.dialect,
        namespace=spec.namespace or "default",
    )

async def _do_health(self, *, ctx=None) -> dict:
    return {"ok": True, "server": "quick-graph", "version": "1.0.0"}

Usage

async def main():
print("=" * 80)
print("Quick Graph Adapter Demo")
print("=" * 80)

async with QuickGraphAdapter() as adapter:
    ctx = OperationContext(request_id="req-4", tenant="acme")

    # Test 1: Capabilities
    caps = await adapter.capabilities()
    print(f"\n✅ Capabilities:")
    print(f"   Server: {caps.server} v{caps.version}")
    print(f"   Supported dialects: {caps.supported_query_dialects}")
    print(f"   Supports streaming: {caps.supports_stream_query}")
    print(f"   Supports bulk vertices: {caps.supports_bulk_vertices}")
    print(f"   Supports batch: {caps.supports_batch}")
    print(f"   Supports schema: {caps.supports_schema}")

    # Test 2: Upsert nodes
    result = await adapter.upsert_nodes(
        UpsertNodesSpec(nodes=[
            Node(
                id=GraphID("user:1"),
                labels=("User",),
                properties={"name": "Ada"}
            ),
            Node(
                id=GraphID("user:2"),
                labels=("User",),
                properties={"name": "Bob"}
            )
        ])
    )
    print(f"\n✅ Upsert Nodes:")
    print(f"   Upserted: {result.upserted_count} nodes")
    print(f"   Failed: {result.failed_count} nodes")

    # Test 3: Query the graph
    query_result = await adapter.query(
        GraphQuerySpec(
            text="MATCH (u:User) RETURN u.name",
            dialect="cypher"
        )
    )
    print(f"\n✅ Query:")
    print(f"   Query: MATCH (u:User) RETURN u.name")
    print(f"   Dialect: {query_result.dialect}")
    print(f"   Records: {query_result.records}")
    print(f"   Summary: {query_result.summary}")

    # Test 4: Check stored nodes
    print(f"\n✅ Storage Check:")
    print(f"   Total nodes in memory: {len(adapter.nodes)}")
    for node_id, node in adapter.nodes.items():
        print(f"   - {node_id}: labels={node.labels}, properties={node.properties}")

    # Test 5: Health check
    health = await adapter.health()
    print(f"\n✅ Health Check:")
    print(f"   OK: {health.get('ok', False)}")
    print(f"   Server: {health.get('server', 'unknown')} v{health.get('version', 'unknown')}")

    print("\n" + "=" * 80)
    print("✅ All tests passed!")
    print("=" * 80)

if name == "main":
asyncio.run(main())


 RAG flow```python
"""
RAG (Retrieval-Augmented Generation) Example
Demonstrates combining Embedding, Vector, and LLM protocols
"""
import asyncio
from corpus_sdk.llm.llm_base import (
    BaseLLMAdapter, OperationContext, LLMCompletion,
    TokenUsage, LLMCapabilities
)
from corpus_sdk.embedding.embedding_base import (
    BaseEmbeddingAdapter, EmbedSpec, EmbeddingVector,
    EmbeddingCapabilities, EmbedResult
)
from corpus_sdk.vector.vector_base import (
    BaseVectorAdapter, VectorCapabilities, QuerySpec, UpsertSpec, UpsertResult,
    QueryResult, Vector, VectorMatch, VectorID
)

# 1. Embedding Adapter
class QuickEmbeddingAdapter(BaseEmbeddingAdapter):
    async def _do_capabilities(self) -> EmbeddingCapabilities:
        return EmbeddingCapabilities(
            server="quick-embeddings",
            version="1.0.0",
            supported_models=("quick-embed-001",),
            max_batch_size=128,
            max_text_length=8192,
        )

    async def _do_embed(self, spec: EmbedSpec, *, ctx=None) -> EmbedResult:
        # Deterministic embedding based on text content
        vec = [hash(spec.text + str(i)) % 1000 / 1000.0 for i in range(384)]
        return EmbedResult(
            embedding=EmbeddingVector(
                vector=vec,
                text=spec.text,
                model=spec.model,
                dimensions=len(vec)
            ),
            model=spec.model,
            text=spec.text,
            tokens_used=len(spec.text.split()),
            truncated=False,
        )

    async def _do_health(self, *, ctx=None) -> dict:
        return {"ok": True, "server": "quick-embeddings"}

# 2. Vector Store Adapter
class QuickVectorAdapter(BaseVectorAdapter):
    def __init__(self):
        super().__init__()
        self.vectors = {}

    async def _do_capabilities(self) -> VectorCapabilities:
        return VectorCapabilities(
            server="quick-vector",
            version="1.0.0",
            max_dimensions=384
        )

    async def _do_upsert(self, spec: UpsertSpec, *, ctx=None) -> UpsertResult:
        ns = spec.namespace or "default"
        if ns not in self.vectors:
            self.vectors[ns] = []
        self.vectors[ns].extend(spec.vectors)

        return UpsertResult(
            upserted_count=len(spec.vectors),
            failed_count=0,
            failures=[]
        )

    async def _do_query(self, spec: QuerySpec, *, ctx=None) -> QueryResult:
        ns = spec.namespace or "default"
        stored = self.vectors.get(ns, [])

        # Cosine similarity
        def cosine_sim(a, b):
            dot = sum(x * y for x, y in zip(a, b))
            mag_a = sum(x * x for x in a) ** 0.5
            mag_b = sum(x * x for x in b) ** 0.5
            return dot / (mag_a * mag_b) if mag_a and mag_b else 0

        matches = []
        for vec in stored:
            score = cosine_sim(spec.vector, vec.vector)
            matches.append(VectorMatch(vector=vec, score=score, distance=1-score))

        matches.sort(key=lambda m: m.score, reverse=True)
        top_k = matches[:spec.top_k] if spec.top_k else matches

        return QueryResult(
            matches=top_k,
            query_vector=spec.vector,
            namespace=ns,
            total_matches=len(top_k),
        )

    async def _do_health(self, *, ctx=None) -> dict:
        return {"ok": True, "server": "quick-vector"}

# 3. LLM Adapter
class QuickLLMAdapter(BaseLLMAdapter):
    async def _do_capabilities(self) -> LLMCapabilities:
        return LLMCapabilities(
            server="quick-llm",
            version="1.0.0",
            model_family="gpt-4",
            max_context_length=8192,
        )

    async def _do_complete(self, messages, model, **kwargs) -> LLMCompletion:
        # Extract the last user message
        user_msg = messages[-1]["content"] if messages else ""

        # Simple mock: generate response based on context presence
        if "Corpus SDK" in user_msg:
            response = "Based on the documentation, Corpus SDK is a protocol suite that provides standardized interfaces for LLM, Embedding, Vector, and Graph operations. It enables backend-agnostic AI applications."
        elif "domains" in user_msg.lower():
            response = "The SDK supports four core domains: LLM (language models), Embedding (text vectorization), Vector (similarity search), and Graph (knowledge graphs)."
        elif "integrate" in user_msg.lower() or "backend" in user_msg.lower():
            response = "To integrate a backend, create an adapter class that inherits from the appropriate base (BaseLLMAdapter, BaseEmbeddingAdapter, etc.) and implement the _do_* hook methods like _do_complete, _do_embed, or _do_query."
        else:

…(正文过长,页面只展示前面部分,完整内容见仓库)

常见问题

8 问
答案由本站依据条目字段整理,不引用上游原文
corpusos 怎么安装?

在客户端按下面的安装命令接入:pip install corpusos。对应的包名是 corpusos。装完在客户端配置里引用同一个包或端点。

corpusos 怎么在 Claude Desktop、Cursor、Cline 里配置?

它的传输方式是stdio · 本地进程,在客户端的 MCP 配置里填好启动命令和参数,保存后完全退出客户端再打开,配置才会生效。

corpusos 收费吗?

本站不代收费用,也没有标注具体价格。是否收费取决于服务本身和背后的接口额度,正式使用前按官方说明确认。

corpusos 需要 API Key 吗?

资料没有标注鉴权方式,是否需要密钥取决于服务本身,接入前按官方文档确认。

corpusos 支持哪些客户端?

资料标注支持 Claude Desktop、Cursor、Cline、Claude Code;其他客户端只要能配置 MCP Server,也能用同样的命令或地址接入。

corpusos 能提供哪些能力?

资料显示能力标签包括 corpusos、agents、ai-agents、ai-infrastructure、anthropic。具体工具清单以官方文档为准。

corpusos 需要什么运行环境?

运行时为 Cross-platform;属于本地进程,需要在本机装好运行环境。

corpusos 是本地还是远程?

它是本地进程(stdio),由客户端在本机拉起。传输方式为stdio · 本地进程。

热门专题

按标签挑服务器
全部专题 →

服务器信息以作者仓库与官方文档为准;分类、传输方式与鉴权方式的中文说明为中文整理,最近核验 2026-04-08。