Skip to content

feat(serve): stdio 외 직접 Streamable HTTP MCP transport 추가 (+선택적 bearer)#8

Open
epruseal wants to merge 10 commits into
AlexAI-MCP:mainfrom
epruseal:feat/serve-streamable-http
Open

feat(serve): stdio 외 직접 Streamable HTTP MCP transport 추가 (+선택적 bearer)#8
epruseal wants to merge 10 commits into
AlexAI-MCP:mainfrom
epruseal:feat/serve-streamable-http

Conversation

@epruseal

Copy link
Copy Markdown
Contributor

동기

opencrab serve는 현재 stdio MCP만 제공합니다. 원격/HTTP로 붙이려면 supergateway 같은 외부 stdio→HTTP 브리지가 필요했습니다. 이 PR은 serve가 직접 Streamable HTTP(2025-03-26) MCP transport를 제공하게 해서 외부 브리지를 불필요하게 만듭니다. stdio는 기본값으로 그대로 유지됩니다(하위호환).

변경

  • opencrab/mcp/server.py_handle_raw에서 handle_request(dict)를 추출해 stdio·HTTP가 JSON-RPC 디스패치를 단일 출처로 공유. initialize가 클라이언트의 protocolVersion을 에코(2024-11-05 stdio / 2025-03-26 HTTP 핸드셰이크 모두 수용).
  • opencrab/mcp/http_app.py (신규) — 공유 FastAPI mcp_router(POST /mcphandle_request 위임, GET 405, DELETE 200, notification→202, 배치 지원) + 경량 create_app. 선택적 Bearer 인증(HMAC compare): 토큰이 --auth-token/--auth-token-file 또는 OPENCRAB_MCP_TOKEN(_FILE)로 주어질 때만 활성, 미설정 시 무인증.
  • opencrab/cli.pyserve --transport [stdio|http] --host --port --auth-token --auth-token-file. http는 uvicorn 단일 워커(chroma PersistentClient 단일 프로세스 제약).
  • opencrab/config.pyMCP_HTTP_HOST(127.0.0.1) / MCP_HTTP_PORT(8765). 토큰은 config에 저장 안 함.
  • 문서(영어) — README HTTP transport 섹션, .env.example, Makefile serve-http.

stateless 설계: 각 POST가 독립 요청/응답(Mcp-Session-Id·서버 푸시 SSE 없음). 모든 툴이 요청-응답형이라 충분. 새 의존성 0(fastapi/uvicorn 이미 필수).

범위 밖 (의도적)

  • apps/api/main.py의 멀티테넌트·인증 인지 /mcp건드리지 않음(별도 표면).
  • 락/파일스토어 전용 로직 없음.

검증

  • 빌드: python -m build 성공, wheel/sdist에 http_app.py 포함, 클린 venv 설치 OK.
  • 회귀: pytest131 passed, 3 skipped (handle_request 추출이 stdio 동작 보존).
  • 기능(임시 데이터·비프로덕션 포트):
    • stdio tools/list 정상.
    • 무인증 HTTP: initialize(protocolVersion 에코)/tools-list/tools-call(content)/notification→202/GET→405/DELETE→200.
    • 인증 HTTP: 무토큰·오답→401, 정답→200, /healthz→200(면제). 파일·OPENCRAB_MCP_TOKEN env 양쪽 확인.

AlexAI-MCP and others added 10 commits May 13, 2026 14:22
…billing

Fix Docker full mode startup and billing events
## 문제

`LocalGraphStore.find_neighbors`의 외부 while 루프 조건
`len(results) < limit`은 노드 한 개를 완전히 처리한 **뒤에야** 평가된다.
기존 코드는 `cur.fetchall()`로 해당 노드의 모든 엣지를 한꺼번에 메모리에 올린
다음 내부 for 루프를 끝까지 돌았기 때문에, 그동안 limit 체크가 전혀 일어나지
않았다.

이로 인해 차수(degree)가 높은 허브 노드 — 예: 온톨로지 지식 그래프에서
"engineer", "persona", "pack" 같은 개념 노드 — 를 탐색할 때, limit(기본값 50)에
도달한 이후에도 수백~수천 회의 불필요한 `_fetch_node_props` SQL 쿼리가 실행됐다.

## 실측 수치

실제 온톨로지 데이터셋(nodes.jsonl 43,476개, edges.jsonl 68,322개)으로 측정:

| 스케일 | 최고 허브 차수 | find_neighbors d1 p50 |
|--------|-------------|----------------------|
| 20,000 노드 |  98차수 | **0.37ms** |
| 43,000 노드 | 615차수 | **11.86ms** ← 32× 급등 |

43,000 노드 시점에 차수 615짜리 허브가 등장하면서, 내부 루프가 ~1,230회
`_fetch_node_props` 쿼리를 모두 실행한 뒤에야 results가 50개를 채웠다.
데이터가 증가할수록 허브 차수도 함께 커지므로, 방치하면 선형 이상으로 열화된다.

## 수정 내용

두 단계 수정을 outgoing / incoming 양방향 모두에 적용했다:

1. **SQL `LIMIT ?`** — `fetchall`이 반환하는 행 자체를 남은 슬롯
   (`remaining = limit - len(results)`)으로 제한한다. 차수 615 허브라도
   이미 results가 0개인 경우 최대 50행만 DB에서 가져온다.

2. **내부 루프 `break`** — pack 필터 등으로 일부 행이 걸러지면
   fetchall로 가져온 `remaining`개 중 실제로 results에 추가되는 비율이
   낮아질 수 있다. SQL LIMIT만으로는 이를 보완할 수 없으므로, for 루프 안에서도
   limit 도달 시 즉시 break해 추가 property 조회를 방지한다.

## 수정 후 성능

동일 데이터셋(43k 노드, 차수 615 허브) 기준:

| depth | 수정 전 | 수정 후 | 개선 |
|-------|---------|---------|------|
| d=1 | 11.86ms | 1.59ms | **7.5×** |
| d=2 | 10.98ms | 1.58ms | **6.9×** |
| d=3 | 10.74ms | 1.56ms | **6.9×** |

## 동작 변경 없음 확인

- 결과 집합의 정확성: 기존 동작과 동일 (허브/일반 노드 모두 정확성 테스트 통과)
- limit 동작: 실제 차수 62인 노드에서 50개 반환 확인
- 일반 노드(차수 1-5): SQL LIMIT과 break 모두 발동하지 않으므로 동작 동일
- 결과 순서: SQLite는 엣지 삽입 순서 기반, Neo4j는 내부 인덱스 순서 기반으로
  이미 두 모드가 동일하지 않았으며, 이 수정으로 추가 변화 없음
Before: OntologyBuilder.add_edge resolved the from/to node types via
a Neo4j Cypher query, gated on `self._neo4j.available`. In local-only
mode the store is a LocalGraphStore (SQLite) and its `run_cypher` is a
no-op stub, so the lookup silently returned [] and both endpoints fell
back to `_space_to_default_type(space)` — flattening every subject-space
edge to `User`, every decision-space edge to the first decision type,
every resource-space edge to `Project`, and every concept-space edge to
`Entity`. Multi-type ontologies (e.g. domain packs that register many
node types per space) lost edge typing entirely in local mode, and
`find_neighbors` / `find_path` queries failed to find the typed neighbors
they expected.

After: both LocalGraphStore and Neo4jStore expose a parallel
`lookup_node_type(node_id) -> str | None`. The builder uses that method
via duck-typing on whichever store was injected, with the per-space
default kept only as a final fallback when the lookup truly returns None.

This restores typed-edge behavior for local-only deployments without
requiring Neo4j, and keeps existing Neo4j-backed deployments working
since the new Neo4jStore.lookup_node_type runs the same Cypher MATCH
that was previously embedded in the builder.

Discovered while building a domain ontology pack that registers many
typed decision/actor nodes in local mode; reproduced via the new
regression test using upstream-native Team / Document types.
fix: BFS find_neighbors 허브 노드 성능 문제 수정 (SQL LIMIT + 내부 루프 조기 종료)
…e-type-resolution

fix(builder): preserve real node types on edges in local-only mode
Extract MCPServer.handle_request(dict) from _handle_raw so the stdio loop and
an HTTP transport can share one JSON-RPC dispatch source. Echo the client's
requested protocolVersion in initialize (honours both 2024-11-05 stdio and
2025-03-26 Streamable HTTP handshakes).
…r auth

- New opencrab/mcp/http_app.py: shared FastAPI mcp_router (POST /mcp dispatch
  via MCPServer.handle_request, GET 405, DELETE 200) + lightweight create_app.
  Optional Bearer auth (HMAC compare); token from --auth-token/--auth-token-file
  or OPENCRAB_MCP_TOKEN(_FILE). Stateless, single worker.
- opencrab serve gains --transport [stdio|http], --host, --port, --auth-token,
  --auth-token-file. stdio stays the default. No new deps (fastapi/uvicorn
  are already required).
- config: MCP_HTTP_HOST (127.0.0.1) / MCP_HTTP_PORT (8765).
README HTTP-transport section, MCP_HTTP_HOST/PORT in .env.example, serve-http
Makefile target.
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.

3 participants