This file contains essential information for AI agents working on this PocketSmith MCP (Model Context Protocol) server project.
Purpose: A comprehensive MCP server providing AI agents with tools to manage budgets, transactions, categories, and financial data via the PocketSmith API.
Technology Stack: TypeScript, Node.js, Zod validation, PocketSmith API client
Template Base: Built from cyanheads/mcp-ts-template
npm run build # Compile TypeScript and make executable
npm run start:stdio # Start server in stdio mode (for Claude Desktop)
npm run start:http # Start server in HTTP mode
npm run lint # Run ESLint
npm run lint:fix # Fix auto-fixable linting issues
npm run format # Format code with Prettiernpm run inspector # Launch MCP Inspector for testing tools
npm run start # Start built server
npm run tree # Generate project structure treesrc/
βββ index.ts # Entry point
βββ config/ # Environment and configuration
βββ mcp-server/
β βββ server.ts # Main server setup and tool registration
β βββ tools/pocketsmith/ # All PocketSmith MCP tools (24 tools)
β β βββ index.ts # Tool exports
β β βββ getAccounts.ts # Account management
β β βββ getTransactions.ts # Transaction operations
β β βββ createTransaction.ts
β β βββ updateTransaction.ts
β β βββ deleteTransaction.ts
β β βββ getCategories.ts # Category management
β β βββ createCategory.ts
β β βββ updateCategory.ts
β β βββ getCategoryRules.ts # Auto-categorization
β β βββ createCategoryRule.ts
β β βββ getBudgets.ts # Budget analysis
β β βββ getBudgetSummary.ts
β β βββ getRecurringEvents.ts # Scheduled transactions
β β βββ getAccountTransactions.ts
β β βββ getTransactionAttachments.ts # Receipt management
β β βββ getUserAttachments.ts
β β βββ createTransactionAttachment.ts
β β βββ getCurrencies.ts # System info
β β βββ getInstitutions.ts
β β βββ getTransactionAccounts.ts
β β βββ getUserSummary.ts # Financial overview
β βββ transports/ # Stdio and HTTP transport
βββ services/
β βββ pocketsmith.ts # PocketSmith API service wrapper
βββ types-global/ # Shared TypeScript types
βββ utils/ # Logging, error handling, security
Each MCP tool follows this consistent pattern:
// toolName.ts
export const ToolNameInputSchema = z.object({...});
export const ToolNameResponseSchema = z.object({...});
export async function toolNameLogic(params, context): Promise<Response> {...}
export const registerToolNameTool = async (server: McpServer): Promise<void> {...}- Create tool file in
src/mcp-server/tools/pocketsmith/ - Export registration function from
src/mcp-server/tools/pocketsmith/index.ts - Import and register in
src/mcp-server/server.ts
- Use
McpErrorwithBaseErrorCodeenum values - Always provide defensive programming for optional API fields
- Use
logger.debug()for detailed logging - Redact sensitive data in logs (API keys, tokens)
- Strict typing: No
anytypes (useRecord<string, unknown>instead) - Zod validation: All inputs/outputs must have Zod schemas
- Defensive programming: Handle optional API fields with
??operators - Type assertions: Use specific types like
{ currency_code?: string }instead ofany
- Files: camelCase (e.g.,
getTransactions.ts) - Functions: camelCase (e.g.,
getTransactionsLogic) - Tool names: snake_case (e.g.,
"get_transactions") - Schema exports: PascalCase (e.g.,
GetTransactionsInputSchema)
- Input validation: Always use Zod schemas
- API service: Use
PocketSmithServiceclass methods - Response structure: Return both
structuredContentandcontentarrays - Context logging: Pass
RequestContextthrough all operations
// In service methods
const apiKey = params.apiKey || process.env.POCKETSMITH_API_KEY;
const accessToken = params.accessToken || process.env.POCKETSMITH_ACCESS_TOKEN;
const service = new PocketSmithService(apiKey, accessToken);- Most endpoints require
userId(get from current user first) - Transaction endpoints often have optional date ranges, search, limits
- Budget endpoints require specific period parameters
- Category endpoints support hierarchical relationships
- Attachment endpoints work with base64 file data
// Always handle optional fields defensively
const processedData = apiResponse.map(item => ({
id: item.id ?? 0,
name: item.name ?? '',
amount: item.amount ?? 0,
// Use optional chaining for nested objects
category: item.category ? {
id: item.category.id ?? 0,
title: item.category.title ?? '',
} : undefined,
}));Required for operation:
POCKETSMITH_API_KEY=your_api_key_here # For personal use
# OR
POCKETSMITH_ACCESS_TOKEN=your_oauth_token_here # For OAuth apps
# Optional
MCP_LOG_LEVEL=debug # Logging level
MCP_TRANSPORT_TYPE=stdio # Transport typenpm run inspector
# Opens web interface at http://localhost:3001
# Test individual tools with sample inputs{
"mcpServers": {
"pocketsmith": {
"command": "node",
"args": ["/path/to/pocketsmith-mcp/dist/index.js"],
"env": {
"POCKETSMITH_API_KEY": "your_key"
}
}
}
}- Check API documentation: Review PocketSmith API endpoints
- Create service method: Add to
src/services/pocketsmith.ts - Create tool file: Follow existing pattern in
src/mcp-server/tools/pocketsmith/ - Define schemas: Input and output Zod schemas
- Implement logic: Handle API calls with error handling
- Register tool: Export from index, import in server.ts
- Test build: Run
npm run buildto verify TypeScript - Test functionality: Use MCP inspector or Claude Desktop
async newServiceMethod(
userId: number,
params: { optional?: string },
context: RequestContext
) {
logger.debug('Calling new service method', { ...context, userId, params });
const { data, error } = await this.client.GET('/endpoint/{id}', {
params: {
path: { id: userId },
query: params.optional ? { param: params.optional } : undefined
}
});
if (error) {
throw new McpError(BaseErrorCode.REQUEST_FAILED, `Failed: ${error}`);
}
return data;
}- Build fails: Check TypeScript errors, fix type mismatches
- Tool not found: Verify registration in server.ts
- API errors: Check API key validity and endpoint URLs
- Claude connection: Verify config file path and restart Claude
npm run build # Check compilation errors
npm run lint # Check code style issues
npm run inspector # Test tools interactively- Use
logger.debug()for detailed information - Include context:
{ ...context, additionalData } - Redact sensitive data:
{ ...params, apiKey: "[REDACTED]" }
- PocketSmith API has rate limits
- Service layer handles errors gracefully
- Consider caching for frequently accessed data
- All tools have comprehensive error handling
- Failed requests return structured error responses
- Transient errors suggest retry strategies
- Never log API keys or tokens
- Use environment variables or secure parameter passing
- Validate all inputs with Zod schemas
- Sanitize user inputs to prevent injection
- Transaction data is sensitive financial information
- Log minimal necessary information
- Respect user privacy in error messages
@modelcontextprotocol/sdk: MCP protocol implementationpocketsmith-ts: PocketSmith API client (local dependency)zod: Runtime type validationwinston: Logging
typescript: Type checking and compilationeslint: Code lintingprettier: Code formatting
- Transaction batch operations
- Advanced budget forecasting
- Category rule templates
- Transaction import/export
- Real-time webhook support
- Multi-currency conversion tools
- Caching layer for frequently accessed data
- Background job processing for large operations
- GraphQL endpoint for complex queries
- WebSocket support for real-time updates
Last Updated: December 2024
Total Tools: 24 MCP tools for comprehensive PocketSmith integration
Status: Production ready, fully typed, comprehensive error handling