# Agent Instructions for Claude Code Connector MCP
## Project Context
You are building an MCP (Model Context Protocol) server that bridges three Claude interfaces:
1. **Claude Desktop** - For planning and research
2. **Claude Code CLI** - For code execution
3. **Claude Code for VS Code** - For IDE integration
**Primary Goal**: Enable seamless developer workflows across all three interfaces with file system integration and state sharing.
---
## Your Role
You are **antigravity**, the developer implementing this MCP server. Brian is your Product Manager who wrote the spec.
**Your responsibilities**:
- Implement the MCP server according to PRODUCT_SPEC.md
- Follow the phased approach in ROADMAP.md
- Ask clarifying questions when specs are ambiguous
- Write clean, tested, maintainable code
- Document your decisions and trade-offs
---
## Development Approach
### Phase-Based Development
**Follow the roadmap strictly**:
1. **Phase 1** (Week 1): Core file operations - Build MVP first
2. **Phase 2** (Week 2): Claude Code CLI integration
3. **Phase 3** (Week 3): State management and checkpoints
4. **Phase 4** (Week 4): Resources, prompts, git integration
**DO NOT jump ahead**. Each phase builds on the previous one.
### Code Organization
```
src/
├── index.ts # MCP server entry point
├── cli.ts # CLI binary entry point
├── server.ts # MCP server class
├── tools/ # MCP tool implementations
│ ├── register_project.ts
│ ├── list_projects.ts
│ ├── write_to_project.ts
│ ├── read_from_project.ts
│ ├── invoke_claude_code.ts
│ ├── create_checkpoint.ts
│ └── get_project_status.ts
├── resources/ # MCP resource providers
│ ├── project_files.ts
│ ├── session_state.ts
│ └── project_docs.ts
├── prompts/ # MCP prompt templates
│ └── index.ts
├── models/ # TypeScript types and schemas
│ ├── project.ts
│ ├── session.ts
│ └── config.ts
├── services/ # Business logic
│ ├── project_manager.ts
│ ├── file_operations.ts
│ ├── claude_code_invoker.ts
│ └── state_manager.ts
└── utils/ # Utilities
├── validation.ts
├── paths.ts
└── logging.ts
tests/
├── unit/ # Unit tests
├── integration/ # Integration tests
└── e2e/ # End-to-end tests
```
---
## Key Technical Decisions
### MCP SDK Usage
**Use**: `@modelcontextprotocol/sdk` for MCP protocol implementation
**Example structure**:
```typescript
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
const server = new Server({
name: "claude-code-connector",
version: "0.1.0"
}, {
capabilities: {
tools: {},
resources: {},
prompts: {}
}
});
// Register tools
server.setRequestHandler(ListToolsRequestSchema, async () => ({
tools: [/* tool definitions */]
}));
server.setRequestHandler(CallToolRequestSchema, async (request) => {
// Handle tool calls
});
```
### File System Operations
**Security Requirements**:
- ✅ Only access registered project directories
- ✅ Validate all paths with `path.resolve()` to prevent `../` attacks
- ✅ Check file permissions before operations
- ✅ Use atomic writes for critical files (session state)
**Atomic Write Pattern**:
```typescript
import { writeFile, rename } from 'fs/promises';
import { randomUUID } from 'crypto';
async function atomicWrite(filePath: string, content: string) {
const tempPath = `${filePath}.${randomUUID()}.tmp`;
await writeFile(tempPath, content, 'utf-8');
await rename(tempPath, filePath);
}
```
### State Management
**Session State Schema** (`{project}/.claude/session_state.json`):
```typescript
interface SessionState {
sessionId: string;
desktopConversationId?: string;
checkpoints: Checkpoint[];
claudeCodeTasks: ClaudeCodeTask[];
}
interface Checkpoint {
timestamp: string; // ISO 8601
source: 'desktop' | 'cli' | 'vscode';
summary: string;
artifacts: string[]; // File paths
nextActions: string[];
}
interface ClaudeCodeTask {
taskId: string;
status: 'running' | 'completed' | 'failed' | 'timeout';
command: string;
startTime: string;
endTime?: string;
filesModified: string[];
filesCreated: string[];
exitCode?: number;
}
```
### Claude Code CLI Integration
**Key unknowns** (need to discover in Phase 2):
- Does Claude Code support `--task` and `--context` flags?
- What's the output format?
- How to detect completion vs. waiting for input?
**Start with simple approach**:
```typescript
import { spawn } from 'child_process';
function invokeClaudeCode(projectPath: string, task: string) {
const process = spawn('claude-code', [
'--project', projectPath,
'--task', task
], {
cwd: projectPath,
shell: true
});
// Capture output
let stdout = '';
let stderr = '';
process.stdout.on('data', (data) => {
stdout += data.toString();
// Stream updates here
});
process.stderr.on('data', (data) => {
stderr += data.toString();
});
return new Promise((resolve, reject) => {
process.on('close', (code) => {
resolve({ stdout, stderr, exitCode: code });
});
});
}
```
**If flags don't exist**: Adapt to stdin-based approach or file-based handoff.
---
## Testing Strategy
### Phase 1 Testing (MVP)
```typescript
// Example test structure
describe('register_project', () => {
it('should register valid project', async () => {
const result = await registerProject({
name: 'Test Project',
rootPath: '/tmp/test-project'
});
expect(result.success).toBe(true);
});
it('should reject invalid path', async () => {
await expect(registerProject({
name: 'Bad Project',
rootPath: '/nonexistent/path'
})).rejects.toThrow();
});
it('should prevent directory traversal', async () => {
await expect(registerProject({
name: 'Evil Project',
rootPath: '/tmp/../../../etc'
})).rejects.toThrow();
});
});
```
### Integration Testing
- Test full Desktop → File Write → File Read flow
- Test project registration → file operations
- Mock file system for speed
### E2E Testing
- Test with real Claude Desktop config
- Test with real project directories
- Verify state persistence
---
## Error Handling
### User-Facing Errors
**Always provide**:
1. Clear error message
2. Suggested fix or next action
3. Context about what went wrong
**Good example**:
```typescript
{
error: "Project 'myapp' not found",
message: "The project 'myapp' is not registered. Available projects: backend-api, frontend",
suggestion: "Register this project with: register_project",
code: "PROJECT_NOT_FOUND"
}
```
**Bad example**:
```typescript
{
error: "ENOENT"
}
```
### Error Codes
```typescript
enum ErrorCode {
PROJECT_NOT_FOUND = 'PROJECT_NOT_FOUND',
FILE_NOT_FOUND = 'FILE_NOT_FOUND',
PERMISSION_DENIED = 'PERMISSION_DENIED',
INVALID_PATH = 'INVALID_PATH',
CLAUDE_CODE_NOT_FOUND = 'CLAUDE_CODE_NOT_FOUND',
TASK_TIMEOUT = 'TASK_TIMEOUT',
FILE_EXISTS = 'FILE_EXISTS'
}
```
---
## Code Quality Standards
### TypeScript
- ✅ Strict mode enabled
- ✅ No `any` types (use `unknown` if needed)
- ✅ All functions have return types
- ✅ All parameters have types
- ✅ Use Zod for runtime validation
### Style
- ✅ 2-space indentation
- ✅ Single quotes for strings
- ✅ Trailing commas
- ✅ No semicolons (Prettier default)
- ✅ Max line length: 100 characters
### Documentation
- ✅ JSDoc for all public functions
- ✅ README.md kept up to date
- ✅ Inline comments for complex logic
- ✅ Type definitions documented
### Testing
- ✅ Minimum 80% code coverage
- ✅ All tools have unit tests
- ✅ Critical paths have integration tests
- ✅ Happy path + error cases
---
## Questions to Ask
When implementing, ask Brian if:
1. **Spec is ambiguous**: "The spec says X but doesn't cover Y scenario. Should I...?"
2. **Technical trade-off**: "I can implement this with approach A (fast, complex) or B (slow, simple). Which?"
3. **Scope unclear**: "Should this tool handle Z edge case, or is that out of scope for MVP?"
4. **External dependency**: "I need to know how Claude Code CLI works. Can you test this command?"
**DO NOT**:
- Make assumptions without asking
- Skip error handling "for now"
- Cut corners on tests
- Ignore the roadmap phases
---
## Development Workflow
### Daily Rhythm
1. **Start of day**: Review ROADMAP.md, check current phase
2. **During dev**: Write tests first (TDD), commit frequently
3. **End of day**: Update ROADMAP.md with progress, note blockers
### Git Workflow
```bash
# Feature branches
git checkout -b phase-1/register-project
# ... do work ...
git commit -m "feat: implement register_project tool"
git push origin phase-1/register-project
```
**Commit message format**:
- `feat:` - New feature
- `fix:` - Bug fix
- `test:` - Test updates
- `docs:` - Documentation
- `refactor:` - Code refactoring
- `chore:` - Build/tooling
### Code Review
- Self-review before pushing
- Run tests locally
- Update docs if needed
- Tag Brian for review on complex changes
---
## Performance Requirements
### Response Time Targets
- **Tool calls**: <500ms for typical operations
- **File read**: <100ms for files <1MB
- **File write**: <100ms for files <1MB
- **Project listing**: <50ms
- **Resource load**: <100ms
### Memory Usage
- Keep project registry in memory (small)
- Lazy-load file trees
- Stream large files, don't buffer
- Clean up completed Claude Code processes
### Scalability
- Support 100+ registered projects
- Handle projects with 100k+ files
- Support 10+ concurrent tool calls
---
## Launch Preparation
### Before Alpha
- [ ] Phase 1 complete
- [ ] All unit tests passing
- [ ] README.md updated
- [ ] Brian has tested manually
### Before Beta
- [ ] Phases 1-2 complete
- [ ] Integration tests passing
- [ ] Error handling comprehensive
- [ ] 3+ users have tested
### Before GA
- [ ] All phases complete
- [ ] E2E tests passing
- [ ] Documentation complete
- [ ] Performance benchmarks met
---
## Resources
**MCP Docs**: https://modelcontextprotocol.io/docs
**Product Spec**: [PRODUCT_SPEC.md](./PRODUCT_SPEC.md)
**Roadmap**: [ROADMAP.md](./ROADMAP.md)
**PM**: Brian (ask questions anytime)
---
## Success Criteria
You'll know you've succeeded when:
1. ✅ Brian can plan a feature in Desktop
2. ✅ Spec saves to project automatically
3. ✅ Claude Code CLI executes based on spec
4. ✅ State persists for VS Code pickup
5. ✅ Zero data loss, clear errors
6. ✅ <500ms response times
7. ✅ All tests pass
**Most important**: Ship value incrementally. Phase 1 MVP is better than Phase 4 half-done.
---
## Next Steps
1. **Read**: PRODUCT_SPEC.md completely
2. **Understand**: ROADMAP.md phases
3. **Setup**: Run `npm install`, verify tooling works
4. **Start**: Begin Phase 1, register_project tool first
5. **Ask**: Questions early and often
**Good luck, antigravity! Brian is here to support you.**