Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
178 changes: 86 additions & 92 deletions CLAUDE.md
Original file line number Diff line number Diff line change
@@ -1,117 +1,111 @@
# CLAUDE.md

This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
This file provides guidance to Claude Code when working with this repository.

## Project Overview
## Repository Structure

Sentry MCP is a Model Context Protocol server that provides access to Sentry's functionality through tools, prompts, and resources.

- Our project in sentry is 'sentry/mcp-server'

## Documentation

All documentation is in the `docs/` directory:

### Core MCP Server

- `architecture.mdc` - MCP server architecture (NOT the web app)
- `common-patterns.mdc` - Reusable code patterns
- `quality-checks.mdc` - Required quality checks

### Implementation Guides

- `adding-tools.mdc` - Adding new MCP tools
- `adding-prompts.mdc` - Adding new MCP prompts
- `adding-resources.mdc` - Adding new MCP resources

### Technical References

- `api-patterns.mdc` - Sentry API client usage
- `testing.mdc` - Testing strategies
- `monitoring.mdc` - Observability patterns
- `security.mdc` - Authentication and security

### Cloudflare Web App (Separate Project)
```
sentry-mcp/
├── packages/
│ ├── mcp-server/ # Main MCP server (tools, prompts, resources)
│ │ ├── src/
│ │ │ ├── tools/ # 19 individual tool modules + utils
│ │ │ ├── prompts.ts # MCP prompts
│ │ │ ├── resources.ts # MCP resources
│ │ │ ├── server.ts # MCP server configuration
│ │ │ ├── api-client/ # Sentry API client
│ │ │ └── internal/ # Shared utilities
│ │ └── scripts/ # Build scripts (tool definitions generation)
│ ├── mcp-cloudflare/ # Cloudflare Worker chat application
│ │ ├── src/
│ │ │ ├── client/ # React frontend
│ │ │ └── server/ # Worker API routes
│ │ └── components.json # Shadcn/ui config
│ ├── mcp-server-evals/ # AI evaluation tests
│ ├── mcp-server-mocks/ # MSW mocks for testing
│ ├── mcp-server-tsconfig/ # Shared TypeScript configs
│ └── mcp-test-client/ # MCP client for testing
└── docs/ # All documentation
├── cloudflare/ # Web app docs
└── llms/ # LLM-specific docs
```

- `cloudflare/` - Documentation for the web chat application
- This is a SEPARATE application that uses MCP, not part of MCP itself
## Core Components Impact Analysis

You should ALWAYS update docs when they are inaccurate or you have learned new relevant information which would add clarity that is otherwise missing.
When making changes, consider these areas:

## Documentation Maintenance
### MCP Server (`packages/mcp-server/`)
- **Tools** (19 modules): Query, create, update Sentry resources
- **Prompts**: Help text and guidance for LLMs
- **Resources**: Static documentation and references
- **API Client**: Sentry API integration layer
- **Server**: MCP protocol handler and error formatting

- **Keep CLAUDE.md and cursor.mdc concise**: These files are navigation aids, not comprehensive docs
- **Reference, don't duplicate**: Point to `docs/` files instead of repeating content
- **Update referenced docs first**: When making changes, update the actual documentation before updating references
- **Avoid redundancy**: Check existing docs before creating new ones (see `docs/llms/documentation-style-guide.mdc`)
### Cloudflare Web App (`packages/mcp-cloudflare/`)
- **Client**: React-based chat interface with UI components
- **Server**: Worker API routes for search, auth, MCP communication
- **Integration**: Uses MCP server for tool execution

## Tool Count Limits
### Testing Infrastructure
- **Unit Tests**: Co-located with each component
- **Mocks**: Realistic API responses in `mcp-server-mocks/`
- **Evaluations**: AI-driven integration tests in `mcp-server-evals/`
- **Test Client**: Interactive MCP testing in `mcp-test-client/`

**IMPORTANT**: AI agents have a hard cap of 45 total tools. Sentry MCP must:
- Target ~20 tools (current best practice)
- Never exceed 25 tools (absolute maximum)
- This limit exists in Cursor and possibly other tools
### Build System
- **Tool Definitions**: Auto-generated JSON schemas for client consumption
- **TypeScript Config**: Shared configurations in `mcp-server-tsconfig/`
- **Packaging**: Multiple package coordination

## Critical Quality Checks
## 🔴 CRITICAL: Pre-Development Requirements

**After ANY code changes, you MUST run:**
**MANDATORY READING before ANY code changes:**

```bash
pnpm -w run lint:fix # Fix linting issues
pnpm tsc # Check TypeScript types
pnpm test # Run all tests
```
### MCP Component Development
- **Tools**: MUST read `docs/adding-tools.mdc`
- **Prompts**: MUST read `docs/adding-prompts.mdc`
- **Resources**: MUST read `docs/adding-resources.mdc`
- **Testing**: MUST read `docs/testing.mdc` for all components

**DO NOT proceed if any check fails.**
### Code Changes
- MUST read `docs/common-patterns.mdc` for established patterns
- MUST read `docs/api-patterns.mdc` for API usage
- MUST verify component count limits (tools: ~20 max, prompts/resources: reasonable limits)

## Essential Commands
## Documentation Maintenance Requirements

```bash
# Development
pnpm dev # Start all dev servers
pnpm build # Build all packages
pnpm inspector # Test tools interactively
**MANDATORY: Documentation MUST be updated when making code changes**
- Documentation updates are not optional - they are part of completing any task
- CLAUDE.md ↔ cursor.mdc must stay synchronized
- Update relevant docs for tools, prompts, resources, API patterns, or architecture changes

# Testing
pnpm test # Unit tests
pnpm eval # Evaluation tests (needs OPENAI_API_KEY)
## Code Validation Requirements

# MCP Client Testing
pnpm start:client # Interactive MCP client (needs ANTHROPIC_API_KEY)
pnpm start:client:local # Use local stdio server
**MANDATORY after ANY code changes:**
- Run `pnpm run tsc` to verify type safety
- Run `pnpm run lint` to check code style
- Run `pnpm run test` for affected components
- See `docs/quality-checks.mdc` for complete checklist

# Deployment
pnpm deploy # Deploy to Cloudflare
```
## Component Limits

## Quick Start
**IMPORTANT**:
- **Tools**: Target ~20, never exceed 25 (AI agent hard limitations)
- **Prompts**: Keep reasonable, well-documented
- **Resources**: Keep reasonable, well-documented

1. Install dependencies: `pnpm install`
2. For local testing: `pnpm start:stdio --access-token=<token>`
3. For development: `pnpm dev`
4. For client testing: `pnpm start:client` (requires ANTHROPIC_API_KEY)
## Documentation Directory

## Claude Code-Specific Notes
- `docs/adding-tools.mdc` - Tool development
- `docs/adding-prompts.mdc` - Prompt development
- `docs/adding-resources.mdc` - Resource development
- `docs/testing.mdc` - Testing requirements for all components
- `docs/common-patterns.mdc` - Code patterns
- `docs/api-patterns.mdc` - API usage
- `docs/architecture.mdc` - System design
- `docs/quality-checks.mdc` - Required quality checks

When using Claude Code's MCP integration:
## Claude Code Notes

- The server runs via stdio transport
- Server runs via stdio transport
- Authentication uses access tokens (not OAuth)
- See integration docs in the web UI for setup instructions

## Environment Variables

See specific guides for required environment variables:

- Cloudflare web app: `docs/cloudflare/deployment.md`
- Evaluation tests: `.env.example`
- Local development: Use command-line args
- MCP Client:
- `ANTHROPIC_API_KEY` - Required for AI agent
- `SENTRY_ACCESS_TOKEN` - Required for local stdio mode
- `MCP_HOST` - Optional, defaults to https://mcp.sentry.dev (used by search_docs tool)

## References

- MCP Protocol: https://modelcontextprotocol.io
- Sentry API: https://docs.sentry.io/api/
64 changes: 43 additions & 21 deletions docs/adding-tools.mdc
Original file line number Diff line number Diff line change
Expand Up @@ -22,19 +22,23 @@ Before adding a new tool, consider if it could be:
## Tool Structure

Each tool consists of:
1. **Definition** - Schema in `toolDefinitions.ts`
2. **Handler** - Logic in `tools.ts`
3. **Tests** - Unit tests in `tools.test.ts`
4. **Mocks** - API responses in `mcp-server-mocks`
5. **Evals** - Integration tests (use sparingly)
1. **Tool Module** - Single file in `src/tools/your-tool-name.ts` with definition and handler
2. **Tests** - Unit tests in `src/tools/your-tool-name.test.ts`
3. **Mocks** - API responses in `mcp-server-mocks`
4. **Evals** - Integration tests (use sparingly)

## Step 1: Define the Tool
## Step 1: Create the Tool Module

Add to `packages/mcp-server/src/toolDefinitions.ts`:
Create `packages/mcp-server/src/tools/your-tool-name.ts`:

```typescript
{
name: "your_tool_name" as const,
import { z } from "zod";
import { defineTool } from "./utils/defineTool";
import { apiServiceFromContext } from "./utils/api-utils";
import type { ServerContext } from "../types";

export default defineTool({
name: "your_tool_name",
description: [
"One-line summary.",
"",
Expand All @@ -50,12 +54,15 @@ Add to `packages/mcp-server/src/toolDefinitions.ts`:
"- Parameter interpretation hints",
"</hints>",
].join("\n"),
paramsSchema: {
organizationSlug: ParamOrganizationSlug,
regionUrl: ParamRegionUrl.optional(),
inputSchema: {
organizationSlug: z.string().describe("The organization's slug"),
regionUrl: z.string().optional().describe("Optional region URL"),
yourParam: z.string().describe("What values are expected"),
},
}
async handler(params, context: ServerContext) {
// Implementation here
},
});
```

### Writing LLM-Friendly Descriptions
Expand All @@ -68,16 +75,16 @@ Critical for LLM success:

## Step 2: Implement the Handler

Add to `packages/mcp-server/src/tools.ts`:
Add the handler implementation to your tool module:

```typescript
your_tool_name: async (context, params) => {
async handler(params, context: ServerContext) {
// 1. Get API service
const api = apiServiceFromContext(context, {
regionUrl: params.regionUrl,
});

// 2. Validate inputs (see common-patterns.mdc)
// 2. Validate inputs (see common-patterns.mdc#error-handling)
if (!params.organizationSlug) {
throw new UserInputError(
"Organization slug is required. Use find_organizations() to list."
Expand Down Expand Up @@ -105,7 +112,7 @@ your_tool_name: async (context, params) => {
output += "- Next tool to use: `related_tool(param='...')`\n";

return output;
};
}
```

### Response Formatting
Expand All @@ -117,14 +124,23 @@ See `common-patterns.mdc#response-formatting` for:

## Step 3: Add Tests

Unit test in `tools.test.ts`:
Follow comprehensive testing patterns from `testing.mdc` for unit, integration, and evaluation tests.

Create `packages/mcp-server/src/tools/your-tool-name.test.ts`:

```typescript
import { describe, it, expect } from "vitest";
import yourToolName from "./your-tool-name.js";

describe("your_tool_name", () => {
it("returns formatted output", async () => {
const result = await TOOL_HANDLERS.your_tool_name(
mockContext,
{ organizationSlug: "test-org", yourParam: "value" }
const result = await yourToolName.handler(
{ organizationSlug: "test-org", yourParam: "value" },
{
accessToken: "test-token",
userId: "1",
organizationSlug: null,
}
);

expect(result).toMatchInlineSnapshot(`
Expand All @@ -136,6 +152,12 @@ describe("your_tool_name", () => {
});
```

**Testing Requirements:**
- Input validation (see `testing.mdc#testing-error-cases`)
- Error handling (use patterns from `common-patterns.mdc#error-handling`)
- Output formatting with snapshots
- API integration with MSW mocks

**After changing output, update snapshots:**
```bash
cd packages/mcp-server
Expand Down
4 changes: 3 additions & 1 deletion docs/api-patterns.mdc
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ const api = new SentryApiService({
});
```

See: `packages/mcp-server/src/api-utils.ts`
See: `packages/mcp-server/src/api-utils.ts` and `adding-tools.mdc#step-2-implement-the-handler` for usage in tools.

### Common Operations

Expand Down Expand Up @@ -83,6 +83,8 @@ See Zod patterns: `common-patterns.mdc#zod-schema-patterns`

### Type Safety

For testing API patterns, see `testing.mdc#mock-server-setup`

```typescript
// Derive types from schemas
export type Issue = z.infer<typeof IssueSchema>;
Expand Down
4 changes: 4 additions & 0 deletions docs/common-patterns.mdc
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,8 @@ export type ToolParams<T> = z.infer<typeof toolDefinitions[T].parameters>;

## Testing Patterns

For comprehensive testing guidance, see `testing.mdc` and `adding-tools.mdc#step-3-add-tests`.

### Unit Test Structure

```typescript
Expand Down Expand Up @@ -124,6 +126,8 @@ See: `packages/mcp-server/src/test-utils/setup.ts`

## API Patterns

For complete API usage patterns, see `api-patterns.mdc`.

### Service Creation

```typescript
Expand Down
Loading