apollo-cache-copilot
apollo-cache-copilot
Apollo InMemoryCache 정규화 결함을 진단하기 위한 AI 코파일럿 및 MCP 서버 — Apollo DevTools가 존재하지 않는 React Native를 위해 제작되었습니다.
문제
Apollo Client는 모든 결과를 __typename:id 엔티티의 평면 맵으로 정규화하고, 교차 참조를 { "__ref": "Type:id" } 포인터로 저장합니다. 이러한 정규화는 쓰기 시점에는 보이지 않으며 읽기 시점에만 실패합니다 — 대개 그 원인이 된 mutation과는 동떨어진 화면에서 말이죠. 세 가지 실패 유형이 지배적이며, 세 가지 모두 조용히(silent) 발생합니다:
결함 | Apollo가 하는 일 | 증상 |
고아 포인터(Orphaned pointer) — 저장소에 | 필드에 대해 | 빈 행, 예외 없음 |
| 캐시 키를 계산할 수 없어 객체를 인라인으로 저장 | 정상 렌더링, 이후 두 번째 쓰기에서 불일치 발생 |
타입/키 드리프트 — | 동일한 논리 엔티티가 두 개의 키로 존재 | 중복된 목록 항목, 오래된 읽기 |
React Native는 이 모든 문제를 더 악화시킵니다:
Apollo DevTools 없음. 브라우저 확장 프로그램이 주요 캐시 디버거이지만 RN에는 존재하지 않습니다. 대안은
console.log(JSON.stringify(client.cache.extract()))로 수 메가바이트 덩어리를 눈으로 읽는 것입니다.영속화된 캐시.
apollo3-cache-persist+ AsyncStorage는 손상된 캐시가 앱 재시작 후에도 살아남게 만듭니다 — 끈적거리며, 사용자 기기에서만 재현됩니다.오프라인 우선 mutation. 낙관적 응답(optimistic responses)은 설계상 부분 엔티티를 쓰는데, 이는 정확히 결함 1과 2를 유발하는 형태입니다.
긴 세션. 모바일 앱은 며칠씩 상주하므로 브라우저 탭보다 훨씬 오래 드리프트가 누적됩니다.
Related MCP server: mcp-rn-devtools
해결책
탐지는 결정적입니다. 설명은 모델의 몫입니다.
캐시 분석기 —
cache.extract()출력을 순회하며 정확한 경로(User:1.avatar → Avatar:99)와 함께 구조적 결함을 보고합니다. 단순한 그래프 순회 — 모델 없음, 추측 없음, 10MB 스냅샷에서도 실행됩니다.MCP 서버 — 해당 분석기를 개발자가 이미 사용 중인 에이전트에 노출합니다. 에이전트는 전체 캐시를 컨텍스트에 담을 필요 없이, 분석 결과와 관련 서브그래프만 요청합니다.
진단이 "10MB 덩어리를 붙여넣고 눈을 찡그리기"에서 대화로 바뀝니다.
아키텍처
flowchart TD
subgraph client["MCP client — Claude Desktop / Cursor"]
A["Agent (the LLM)"]
end
subgraph server["apollo-cache-copilot (stdio process)"]
T["StdioServerTransport<br/>apollo-copilot mcp"]
R["Tool registry<br/>inspect_dangling_refs<br/>patch_cache<br/>diagnose_cache_graph"]
Z["Zod schemas<br/>parse in, shape out"]
subgraph g["cacheAgentGraph (LangGraph, LLM-free)"]
I["inspectorNode<br/>writes findings"]
RE["reasonerNode<br/>writes proposedPatches"]
P["patcherNode<br/>writes narration"]
I --> RE --> P
end
TOOL1["inspectDanglingRefs()<br/>pure, on a snapshot"]
TOOL2["patchCache()<br/>modify / evict / gc"]
T --> R --> Z --> I
I -.->|calls| TOOL1
P -.->|plans for| TOOL2
end
A <-->|"JSON-RPC 2.0 over stdio"| T
TOOL1 --- CACHE["cache.extract() snapshot"]
TOOL2 --- LIVE["live ApolloCache"]ASCII, 동일한 내용:
MCP client (Claude Desktop, Cursor, any stdio client)
│ JSON-RPC 2.0 ▲
▼ over stdio │ stdout IS the protocol channel —
┌─────────────────────────────────┐ all logs go to stderr
│ StdioServerTransport │
├─────────────────────────────────┤
│ tools: inspect_dangling_refs │ read-only
│ patch_cache │ mutating (dryRun available)
│ diagnose_cache_graph │ read-only, plans only
├─────────────────────────────────┤
│ Zod schemas — parse at the edge │
└───────────────┬─────────────────┘
▼
┌─────────────────────────────────────────────────────┐
│ cacheAgentGraph (LangGraph, deliberately LLM-free)│
│ │
│ INSPECTOR ──────► REASONER ──────► PATCHER │
│ walks the store maps findings narrates the │
│ → findings[] → patch ops plan │
│ │ │ │
│ │ owns `findings` │ owns `proposedPatches` │
└──────┼──────────────────┼────────────────────────────┘
▼ ▼
inspectDanglingRefs() patchCache()
pure, on a snapshot cache.modify / evict / gc on a live cache각 그래프 노드는 정확히 하나의 상태 채널을 소유합니다 — 검사기(inspector)는 findings를 쓰고, 추론기(reasoner)는 proposedPatches를 쓰며, 패처(patcher)는 messages를 씁니다. messages만 누적됩니다. 노드를 다시 실행하면 동일한 캐시를 다시 분석하므로, 다른 곳에 추가하면 두 번째 실행에서 모든 finding이 중복됩니다.
그래프에 LLM이 없는 이유는 무엇인가요? 이 코파일럿이 탐지하는 모든 결함에는 기계적 복구 방법(포인터 정리, 고아 제거)이 있습니다. 모델은 switch가 이미 올바르게 처리하는 결정에 지연 시간, 비용, 비결정성을 추가할 뿐입니다. 그래프는 오케스트레이션으로서 가치가 있으며, 모델은 MCP 클라이언트에 존재하여 finding을 이를 작성한 mutation이나 fragment와 연관시킵니다.
설치
npm install @indianic/apollo-cache-copilot
# or, from a checkout
npm install && npm run buildNode.js ≥ 20 필요(vitest 4와 @langchain/core 모두 요구하며, CI는 20과 22를 포함). @apollo/client(v3.8+ 또는 v4), react, react-native는 peer 의존성입니다 — 패키지는 앱의 복사본을 사용합니다.
라이브러리 사용법
ESM 전용. 패키지에 타입이 포함되어 있습니다.
inspectDanglingRefs — 스냅샷 감사
순수하고 동기적입니다. cache.extract() 출력을 받아 findings + 통계를 반환합니다.
import { inspectDanglingRefs } from 'apollo-cache-copilot';
const { findings, stats } = inspectDanglingRefs({
cache: client.cache.extract(),
// all optional:
rootIds: ['ROOT_QUERY', 'ROOT_MUTATION'], // reachability roots
includeUnreachable: true, // report gc candidates
includeNormalizationGaps: true, // report un-keyable inline objects
});
console.log(stats);
// { entityCount: 4, refCount: 3, danglingCount: 1, unreachableCount: 1 }
for (const f of findings) {
console.log(f.kind, f.path, f.danglingRef ?? '');
// ORPHANED_REF User:1.avatar Avatar:99
// UNREACHABLE_ENTITY Post:7
}Finding 종류: ORPHANED_REF, UNREACHABLE_ENTITY, MISSING_TYPENAME, MISSING_ID. 모든 finding은 정확한 캐시 경로를 포함합니다.
patchCache — 라이브 캐시에 복구 적용
연산은 선언적 설명자(descriptor)이므로 JSON 왕복에도 살아남습니다. 도구는 이를 cache.modify가 원하는 함수로 재수화(rehydrate)합니다. 순서가 있으며, 실패는 기록되며 던져지지 않으므로 배치 중간의 잘못된 키가 캐시를 반쯤 패치된 상태로 좌초시킬 수 없습니다.
import { patchCache } from 'apollo-cache-copilot';
const { dryRun, results, collected } = patchCache(client.cache, {
operations: [
// drop dangling refs from a list field
{ type: 'modify', id: 'User:1', fields: { posts: { action: 'PRUNE_DANGLING_REFS' } } },
// delete / invalidate / overwrite a field
{ type: 'modify', id: 'User:1', fields: { avatar: { action: 'DELETE' } } },
{ type: 'modify', id: 'User:1', fields: { bio: { action: 'SET', value: 'unset' } } },
// evict an entity, or one field of it
{ type: 'evict', id: 'Post:7' },
{ type: 'evict', id: 'ROOT_QUERY', fieldName: 'user', args: { id: '1' } },
],
gc: true, // run cache.gc() once, after everything lands
dryRun: false, // true = validate only, cache untouched
});
results.forEach((r) => console.log(r.changed, r.error ?? ''));
console.log('collected:', collected); // keys gc() removed필드 액션: DELETE, INVALIDATE, SET(value 포함), PRUNE_DANGLING_REFS.
cacheAgentGraph — 검사 → 추론 → 계획
컴파일된 LangGraph입니다. findings, 적용할 패치 연산, 단계별 설명을 반환합니다. 절대 변경(mutate)하지 않습니다 — 검토 후 proposedPatches를 patchCache에 전달하세요.
import { cacheAgentGraph } from 'apollo-cache-copilot';
const state = await cacheAgentGraph.invoke({ cacheState: client.cache.extract() });
state.messages.forEach((m) => console.log(String(m.content)));
// 2 findings: 1 orphaned ref, 1 unreachable entity.
// ...
// Review, then apply:
patchCache(client.cache, { operations: state.proposedPatches });또한 내보내짐: buildCacheAgentGraph()(컴파일되지 않은 빌더), 개별 노드 inspectorNode / reasonerNode / patcherNode, CacheAgentAnnotation, 모든 Zod 스키마(InspectDanglingRefsInputSchema, PatchCacheInputSchema, …) 및 그 추론 타입, 그리고 MCP 표면(createServer, startStdioServer, runInspectDanglingRefs, runPatchCache, runDiagnoseCacheGraph).
CLI 사용법
apollo-copilot [mcp] Start the stdio MCP server (default when no args)
apollo-copilot inspect FILE Diagnose a JSON cache snapshot and print findingsapollo-copilot inspect <file>
앱에서 캐시를 덤프한 후 읽습니다:
// in the RN app
console.log(JSON.stringify(client.cache.extract()));npx -y -p @indianic/apollo-cache-copilot apollo-copilot inspect ./cache-snapshot.json━━ Cache Diagnostic ━━
Entities: 4 | Refs: 3 | Dangling: 1 | Unreachable: 1
⚠ ORPHANED_REF (1)
• User:1.avatar → Avatar:99
Points at "Avatar:99", which is not in the cache. Reads here return undefined.
🗑 UNREACHABLE_ENTITY (1)
• Post:7
No root reaches this entity; cache.gc() would collect it.깨끗한 캐시는 ✓ Cache is clean: no findings.를 출력합니다.
종료 코드: 0 성공, 1 예기치 않은 실패, 2 잘못된 입력(파일 없음, 읽을 수 없는 파일, 잘못된 JSON, 알 수 없는 명령).
apollo-copilot mcp
stdio에서 MCP 서버를 시작하고 차단합니다. MCP 클라이언트가 프로세스를 소유할 때만 유용합니다 — 아래 참조. apollo-copilot-mcp는 동일한 기능의 레거시 별칭입니다.
stdout은 프로토콜 채널입니다. 서버는 stdout에 JSON-RPC만 작성하며 모든 진단은 stderr로 갑니다. 이 경로에
console.log를 절대 추가하지 마세요.
MCP 설정
노출된 도구
도구 | 입력 | 동작 |
|
| 읽기 전용. |
|
| 읽기 전용. 전체 그래프 실행. |
|
| 스냅샷을 일회용 |
patch_cache는 스냅샷을 전달합니다. stdio 서버에는 패처에 넘길 라이브 캐시가 없고 JSON만 있기 때문입니다. 반환된 cache를 자신의 것과 비교하거나 client.cache.restore()로 복원하세요.
모든 도구는 사람이 읽을 수 있는 요약 줄과 기계가 읽을 수 있는 structuredContent를 모두 반환하므로, 구조화된 출력을 이해하지 못하는 클라이언트도 JSON을 얻을 수 있습니다.
Claude Desktop
~/Library/Application Support/Claude/claude_desktop_config.json(macOS) 또는 %APPDATA%\Claude\claude_desktop_config.json(Windows):
{
"mcpServers": {
"apollo-cache-copilot": {
"command": "npx",
"args": ["-y", "-p", "@indianic/apollo-cache-copilot", "apollo-copilot", "mcp"]
}
}
}로컬 체크아웃에서 — 먼저 빌드(npm run build)한 후 절대 경로로 bin을 가리킵니다:
{
"mcpServers": {
"apollo-cache-copilot": {
"command": "node",
"args": ["/absolute/path/to/apollo-cache-copilot/bin/apollo-copilot.js", "mcp"]
}
}
}Claude Desktop을 다시 시작합니다. 도구 메뉴 아래 세 가지 도구가 나타납니다.
Cursor
프로젝트의 .cursor/mcp.json(또는 모든 프로젝트에 대해 ~/.cursor/mcp.json):
{
"mcpServers": {
"apollo-cache-copilot": {
"command": "npx",
"args": ["-y", "-p", "@indianic/apollo-cache-copilot", "apollo-copilot", "mcp"]
}
}
}로컬 체크아웃:
{
"mcpServers": {
"apollo-cache-copilot": {
"command": "node",
"args": ["${workspaceFolder}/bin/apollo-copilot.js", "mcp"]
}
}
}그런 다음 Cursor → Settings → MCP에서 서버가 초록색인지 확인합니다.
그냥 물어보세요
"제 캐시 스냅샷입니다 — 프로필 화면에서 아바타가 왜 비어 있나요?"
에이전트가 diagnose_cache_graph를 호출하고, User:1.avatar → Avatar:99와 제안된 PRUNE_DANGLING_REFS를 받은 후, 엔티티 본문 없이 참조를 작성한 mutation과 연관시킵니다.
개발
npm install
npm run build # tsc -> dist/ (run first: typecheck and tests import dist)
npm run typecheck # tsc --noEmit -p tsconfig.test.json (includes tests)
npm test # vitest runtsconfig.json은 빌드용이며 __tests__ / __mocks__를 제외하므로 게시된 패키지는 도구만 포함합니다. tsconfig.test.json은 모든 것을 타입 검사하고 아무것도 생성하지 않습니다.
성공 지표
# | 지표 | 목표 |
1 | 픽스처 스위트에 대한 탐지 재현율 | 100% — 시드된 모든 결함 발견 |
2 | 정상 스냅샷에 대한 오탐(false positive) | 0 |
3 | 10MB | < 1s |
4 | 정확한 캐시 경로를 포함하는 findings | 100% |
5 | 증상에서 명명된 근본 원인까지의 개발자 시간 | < 5분 (vs. 수 시간) |
6 | 진단당 모델에 전송되는 토큰 | < 10k — findings + 서브그래프, 전체 캐시는 절대 아님 |
라이선스
ISC — LICENSE 참조.
Maintenance
Resources
Unclaimed servers have limited discoverability.
Looking for Admin?
If you are the server author, to access and configure the admin panel.
Related MCP Servers
- AlicenseBqualityFmaintenanceAn MCP server that connects to your React Native application debugger22032MIT
- AlicenseNot gradedqualityBmaintenanceThis MCP server enables real-time debugging and inspection of running React Native apps, providing access to console logs, errors, network requests, navigation state, storage, and performance profiling.1MIT
- AlicenseAqualityAmaintenanceMCP server that gives AI coding agents hands, eyes and a mechanic's ear for React Native development.9202MIT
- AlicenseNot gradedqualityAmaintenanceA plugin-based MCP server for React Native runtime debugging, inspection, and automation via Chrome DevTools Protocol. Works with Expo, bare React Native, and any Metro + Hermes project without app code changes.1,04475MIT
Related MCP Connectors
MCP server for Appcircle mobile CI/CD platform.
MCP server for managing Prisma Postgres.
MCP server for interacting with the Supabase platform
Latest Blog Posts
- Who's Calling? MCP Hosts Are an Identity Blind Spot (And the Spec Knows It)By Om-Shree-0709 on .mcpAgent IdentityOAuth 2.1
- Your AI Chatbot Just Exposed Your CEO's Salary to an InternBy Om-Shree-0709 on .Agent IdentityMCP SecurityOAuth Delegation
- Why MCP Servers Need Execution Sandboxing (And Why Your Current Stack Isn't Enough)By Om-Shree-0709 on .Agentic AiPrompt InjectionWebAssembly
MCP directory API
We provide all the information about MCP servers via our MCP API.
curl -X GET 'https://glama.ai/api/mcp/v1/servers/nihar777/apollo-cache-copilot'
If you have feedback or need assistance with the MCP directory API, please join our Discord server