### Run Basic Setup Example with npx tsx Source: https://github.com/badlogic/lemmy/blob/main/packages/lemmy-tools/examples/README.md Demonstrates how to run the basic setup example using `npx tsx`. This example showcases the default configuration with all built-in tools loaded. ```bash npx tsx examples/01-basic-setup.ts ``` -------------------------------- ### Install and Run Project (npm) Source: https://github.com/badlogic/lemmy/blob/main/apps/red-teaming/README.md Installs project dependencies, builds the TypeScript code, and starts the application. Includes a command for direct TypeScript execution during development. ```bash npm install npm run build npm run start # Or for development: npm run run # Direct TypeScript execution ``` -------------------------------- ### Install MCP Server Packages Source: https://github.com/badlogic/lemmy/blob/main/packages/lemmy-tools/examples/README.md Installs the necessary MCP server packages for filesystem and puppeteer integration. These packages are required for the MCP integration examples. ```bash npm install @modelcontextprotocol/server-filesystem npm install @modelcontextprotocol/server-puppeteer ``` -------------------------------- ### Run MCP Integration Example with npx tsx Source: https://github.com/badlogic/lemmy/blob/main/packages/lemmy-tools/examples/README.md Demonstrates running the MCP integration example using `npx tsx`. This example requires MCP server packages to be installed and showcases integration with filesystem and puppeteer MCP servers. ```bash npx tsx examples/03-mcp-integration.ts ``` -------------------------------- ### Development Setup and Testing Source: https://github.com/badlogic/lemmy/blob/main/apps/claude-bridge/README.md Clone the repository, install dependencies, and run development commands. The `npm run dev` command starts compilation in watch mode. Use `npx tsx` for on-the-fly compilation and testing. Various npm scripts are available for running different sets of tests. ```bash git clone https://github.com/badlogic/lemmy cd lemmy && npm install && npm run dev npx tsx src/cli.ts npm run test:all # All tests npm run test:unit # Unit tests npm run test:core # CLI functionality npm run test:tools # Tool integration npm run test:providers # Multi-provider ``` -------------------------------- ### Run Interactive Chat Application Example with npx tsx Source: https://github.com/badlogic/lemmy/blob/main/packages/lemmy-tools/examples/README.md Demonstrates running the interactive chat application example using `npx tsx`. This example provides a complete application integrating lemmy-tools, including command handling and graceful shutdown. ```bash npx tsx examples/06-chat-app.ts ``` -------------------------------- ### Run Selective Tool Loading Example with npx tsx Source: https://github.com/badlogic/lemmy/blob/main/packages/lemmy-tools/examples/README.md Shows how to execute the selective tool loading example using `npx tsx`. This example focuses on loading only specific tools, such as filesystem and shell tools, excluding web tools for enhanced security. ```bash npx tsx examples/02-selective-tools.ts ``` -------------------------------- ### Run Tool Cancellation Example with npx tsx Source: https://github.com/badlogic/lemmy/blob/main/packages/lemmy-tools/examples/README.md Illustrates how to run the tool cancellation example using `npx tsx`. This example highlights automatic timeouts and manual cancellation for long-running tool operations, crucial for maintaining UI responsiveness. ```bash npx tsx examples/04-tool-cancellation.ts ``` -------------------------------- ### Run Custom Tool Development Example with npx tsx Source: https://github.com/badlogic/lemmy/blob/main/packages/lemmy-tools/examples/README.md Shows how to execute the custom tool development example using `npx tsx`. This example focuses on creating custom tools with Zod schemas, including error handling, validation, and platform-aware functionality. ```bash npx tsx examples/05-custom-tool.ts ``` -------------------------------- ### Quick Setup Workflow for Lemmy CLI Source: https://github.com/badlogic/lemmy/blob/main/apps/lemmy-chat/README.md Demonstrates the initial setup and basic usage of the Lemmy CLI. It covers setting default provider and model, and initiating simple chat interactions. ```bash # 1. Set your preferred provider and model lemmy-chat defaults anthropic -m claude-3-5-sonnet-20241022 # 2. Start using without repetitive options lemmy-chat "Hello!" lemmy-chat chat lemmy-chat -i image.png "Describe this" ``` -------------------------------- ### Quick Start: Initialize Lemmy Client with Built-in Tools Source: https://github.com/badlogic/lemmy/blob/main/packages/lemmy-tools/README.md Demonstrates how to initialize the lemmy client and context, then add all available built-in tools to the context. This allows the LLM to access file operations, shell commands, and more. ```typescript import { createAnthropicClient, createContext } from "@mariozechner/lemmy"; import { getBuiltinTools } from "@mariozechner/lemmy-tools"; // Create client and context const client = createAnthropicClient({ model: "claude-3-5-sonnet-20241022" }); const context = createContext(); // Add all built-in tools const tools = getBuiltinTools(); tools.forEach((tool) => context.addTool(tool)); // Now your LLM has access to tools! const result = await client.ask("List files in the current directory", { context }); ``` -------------------------------- ### Build and Run lemmy-chat Source: https://github.com/badlogic/lemmy/blob/main/apps/lemmy-chat/README.md Commands to build, install, set API keys, configure defaults, and start the lemmy-chat application. Requires Node.js and npm. ```bash # Build and install npm run build npm run install-global # Set API keys export ANTHROPIC_API_KEY="sk-..." export OPENAI_API_KEY="sk-..." export GOOGLE_API_KEY="..." # Set your defaults lemmy-chat defaults anthropic -m claude-3-5-sonnet-20241022 # Start chatting lemmy-chat chat ``` -------------------------------- ### Install @mariozechner/lemmy-tools Source: https://github.com/badlogic/lemmy/blob/main/packages/lemmy-tools/README.md Installs the @mariozechner/lemmy-tools package using npm. This is the first step to using the library. ```bash npm install @mariozechner/lemmy-tools ``` -------------------------------- ### Install Dependencies for Development Source: https://github.com/badlogic/lemmy/blob/main/apps/claude-trace/README.md Installs project dependencies required for development using npm. This command should be run in the project's root directory. ```bash npm install ``` -------------------------------- ### Install and Use claude-trace CLI (Bash) Source: https://context7.com/badlogic/lemmy/llms.txt A command-line tool for recording and visualizing Claude Code interactions, including system prompts and tool outputs. It can be used to start tracing, include all API requests, run with specific Claude arguments, generate HTML reports, create conversation indexes, and extract OAuth tokens. Logs are saved to `.claude-trace/`. ```bash # Install globally npm install -g @mariozechner/claude-trace # Start Claude Code with logging claude-trace # Include all API requests (not just substantial conversations) claude-trace --include-all-requests # Run with specific Claude arguments claude-trace --run-with chat --model sonnet-3.5 # Generate HTML report from existing logs claude-trace --generate-html logs.jsonl report.html # Generate conversation index with AI summaries claude-trace --index # Extract OAuth token claude-trace --extract-token ``` -------------------------------- ### Tool Registration Patterns in TypeScript Source: https://github.com/badlogic/lemmy/blob/main/packages/lemmy-tools/examples/README.md Demonstrates different methods for registering tools with the lemmy-tools context. This includes registering all built-in tools, a selective set of tools, and custom-defined tools. ```typescript // All tools const tools = getBuiltinTools(); tools.forEach((tool) => context.addTool(tool)); // Selective tools const selectedTools = [bashTool, readTool, writeTool]; selectedTools.forEach((tool) => context.addTool(tool)); // Custom tools const customTool = defineTool({ /* ... */ }); context.addTool(customTool); ``` -------------------------------- ### Develop Custom CLI Tests with Framework Utilities Source: https://github.com/badlogic/lemmy/blob/main/apps/claude-bridge/test/README.md This TypeScript example demonstrates creating CLI tests. It shows how to use pre-built test creators like `createBasicBridgeTest` and `createToolTest`, and also how to construct fully custom CLI tests using `CLITestRunner`. The custom test includes setup, running the CLI test with specific parameters, validating logs, and cleanup. ```typescript import { CLITestRunner, createBasicBridgeTest, createToolTest, Test } from "./framework.js"; // Use pre-built test creators const bridgeTest = createBasicBridgeTest("openai", "gpt-4o"); const toolTest = createToolTest("Bash", "Use the Bash tool to run 'echo hello'"); // Or create custom CLI tests const customTest: Test = { name: "Custom CLI Test", run: async () => { const runner = new CLITestRunner("custom-test"); await runner.setup(); try { const result = await runner.runCLITest({ provider: "openai", model: "gpt-4o", prompt: "Test prompt", expectedInLogs: ["expected content"], unexpectedInLogs: ["error content"], }); const validation = runner.validateLogs(result.logs, options); await runner.cleanup(); return { name: "Custom CLI Test", success: validation.success, message: validation.success ? "Test passed" : "Test failed", duration: 0, details: validation.details, }; } catch (error) { await runner.cleanup(); throw error; } }, }; ``` -------------------------------- ### Install and Run claude-bridge CLI Source: https://github.com/badlogic/lemmy/blob/main/apps/claude-bridge/README.md Install the claude-bridge package globally using npm and run the CLI for various LLM providers. You can set API keys as environment variables or specify them per command. Examples include running with OpenAI, local Ollama, OpenRouter, and Groq. ```bash npm install -g @mariozechner/claude-bridge # Set API keys (optional - can specify per-command with --apiKey) export OPENAI_API_KEY=sk-... export GOOGLE_API_KEY=... # Discovery workflow claude-bridge # Show available providers claude-bridge openai # Show OpenAI models claude-bridge openai gpt-4o # Run Claude Code with GPT-4 # Custom API key claude-bridge openai gpt-4o --apiKey sk-... # Local Ollama claude-bridge openai llama3.2 --baseURL http://localhost:11434/v1 # OpenRouter claude-bridge openai gpt-4o --baseURL https://openrouter.ai/api/v1 --apiKey sk-or-... # Groq claude-bridge openai moonshotai/kimi-k2-instruct --max-output-tokens 16000 --baseURL https://api.groq.com/openai/v1 --apiKey gsk_O... # Enable debug logs claude-bridge openai gpt-4o --debug # Spy on Claude ↔ Anthropic communication claude-bridge --trace -p "Hello world" # Pass Claude Code arguments after claude-bridge arguments claude-bridge google gemini-2.5-pro-preview-05-06 --resume --continue claude-bridge openai o4-mini -p "Hello world" ``` -------------------------------- ### MCP Configuration for Servers Source: https://github.com/badlogic/lemmy/blob/main/packages/lemmy-tools/README.md Provides an example of MCP configuration, defining various servers like filesystem, puppeteer, and sqlite with their respective commands, arguments, and timeouts. This configuration is used to set up and manage MCP server connections. ```typescript const mcpConfig = { servers: { filesystem: { command: "npx", args: ["@modelcontextprotocol/server-filesystem", "/path/to/root"], timeout: 10000, }, puppeteer: { command: "npx", args: ["@modelcontextprotocol/server-puppeteer"], timeout: 30000, }, }, }; ``` -------------------------------- ### Initialize and Run a Basic TUI Application with Lemmy-TUI Source: https://github.com/badlogic/lemmy/blob/main/packages/lemmy-tui/README.md Demonstrates how to set up a simple terminal UI application using the lemmy-tui framework. It covers creating TUI manager, adding components like headers, containers, and text editors, setting focus, handling user input for the editor, and starting the UI. ```typescript import { TUI, Container, TextComponent, TextEditor } from "@mariozechner/lemmy-tui"; // Create TUI manager const ui = new TUI(); // Create components const header = new TextComponent("🚀 My TUI App"); const chatContainer = new Container(); const editor = new TextEditor(); // Add components to UI ui.addChild(header); ui.addChild(chatContainer); ui.addChild(editor); // Set focus to the editor ui.setFocus(editor); // Handle editor submissions editor.onSubmit = (text: string) => { if (text.trim()) { const message = new TextComponent(`💬 ${text}`); chatContainer.addChild(message); ui.requestRender(); } }; // Start the UI ui.start(); ``` -------------------------------- ### Install Snap Happy CLI Source: https://github.com/badlogic/lemmy/blob/main/apps/snap-happy/README.md Installs the Snap Happy command-line interface globally using npm. This command is used to set up the MCP server for AI assistants. ```bash npm install -g @mariozechner/snap-happy ``` -------------------------------- ### Run claude-trace in Development Mode Source: https://github.com/badlogic/lemmy/blob/main/apps/claude-trace/README.md Starts the development server with file watching for both the main application and the frontend. This allows for live updates during development. ```bash npm run dev ``` -------------------------------- ### MCP Integration Pattern in TypeScript Source: https://github.com/badlogic/lemmy/blob/main/packages/lemmy-tools/examples/README.md Illustrates how to set up and use MCP (Model Context Protocol) servers with lemmy-tools. This involves registering MCP servers and then retrieving and adding their available tools to the context. ```typescript const mcpRegistry = new MCPRegistry(); await mcpRegistry.registerServer("name", { command: "npx", args: ["@modelcontextprotocol/server-name"], timeout: 30000, }); const mcpTools = await mcpRegistry.getAvailableTools(); mcpTools.forEach((tool) => context.addTool(tool)); ``` -------------------------------- ### Install claude-trace CLI Source: https://github.com/badlogic/lemmy/blob/main/apps/claude-trace/README.md Installs the claude-trace command-line interface globally using npm. This makes the 'claude-trace' command available in your terminal. ```bash npm install -g @mariozechner/claude-trace ``` -------------------------------- ### Set API Key (Bash) Source: https://github.com/badlogic/lemmy/blob/main/apps/red-teaming/README.md Sets the environment variable for the OpenAI or Anthropic API key. This is a prerequisite for running the AI model. ```bash export OPENAI_API_KEY="your-key-here" # or export ANTHROPIC_API_KEY="your-key-here" ``` -------------------------------- ### Install Lemmy TypeScript Library Source: https://github.com/badlogic/lemmy/blob/main/packages/lemmy/README.md Installs the Lemmy library using npm. This is the first step to integrating AI capabilities into your TypeScript applications. ```bash npm install @mariozechner/lemmy ``` -------------------------------- ### Implement Multi-step Tool Workflows with Lemmy Source: https://context7.com/badlogic/lemmy/llms.txt Shows how to manage complex workflows where the LLM might need to call multiple tools sequentially. This example defines two tools, `fetchWeather` and `formatReport`, and orchestrates their execution through a loop that continues as long as the model requests tool calls. ```typescript import { lemmy, Context, toAskInput } from "@mariozechner/lemmy"; import { z } from "zod"; // Define multiple tools const fetchWeather = { name: "fetch_weather", description: "Get current weather for a city", schema: z.object({ city: z.string() }), execute: async ({ city }) => ({ temperature: 72, condition: "sunny", city }), }; const formatReport = { name: "format_report", description: "Format data into a readable report", schema: z.object({ data: z.string(), format: z.enum(["brief", "detailed"]) }), execute: async ({ data, format }) => ({ report: `[${format}] ${data}` }), }; const context = new Context(); context.addTool(fetchWeather); context.addTool(formatReport); const claude = lemmy.anthropic({ apiKey: "sk-...", model: "claude-3-5-sonnet-20241022", }); // Start multi-step workflow let currentResult = await claude.ask( "Get the weather for San Francisco and format it as a brief report", { context } ); // Loop until we get a final text response while (currentResult.type === "success" && currentResult.stopReason === "tool_call") { const toolResults = await context.executeTools(currentResult.message.toolCalls!); // eslint-disable-line @typescript-eslint/no-non-null-assertion // Log each tool execution for debugging toolResults.forEach((result, i) => { const toolName = currentResult.message.toolCalls![i].name; // eslint-disable-line @typescript-eslint/no-non-null-assertion console.log(`[${toolName}]:`, result.success ? result.result : result.error); }); currentResult = await claude.ask(toAskInput(toolResults), { context }); } if (currentResult.type === "success") { console.log("Final response:", currentResult.message.content); // Output: "Here's your weather report: [brief] San Francisco - 72°F and sunny" } ``` -------------------------------- ### Create LLM Clients with Lemmy Factory Source: https://context7.com/badlogic/lemmy/llms.txt Demonstrates how to create clients for different LLM providers (Anthropic Claude, OpenAI, Google Gemini) using the unified `lemmy` factory object. It shows basic API key and model configuration, and a simple conversation example. ```typescript import { lemmy, Context } from "@mariozechner/lemmy"; // Create Anthropic Claude client const claude = lemmy.anthropic({ apiKey: process.env.ANTHROPIC_API_KEY, model: "claude-3-5-sonnet-20241022", }); // Create OpenAI client const openai = lemmy.openai({ apiKey: process.env.OPENAI_API_KEY, model: "gpt-4o", }); // Create Google Gemini client const google = lemmy.google({ apiKey: process.env.GOOGLE_API_KEY, model: "gemini-1.5-pro", }); // Simple conversation const result = await claude.ask("Hello!"); if (result.type === "success") { console.log(result.message.content); // Output: "Hello! How can I help you today?" } ``` -------------------------------- ### Start claude-trace Logging Source: https://github.com/badlogic/lemmy/blob/main/apps/claude-trace/README.md Starts the claude-trace tool to log interactions with Claude Code. By default, it logs substantial conversations. Options are available to include all API requests or run with specific Claude arguments. ```bash # Start Claude Code with logging claude-trace # Include all API requests (by default, only substantial conversations are logged) claude-trace --include-all-requests # Run Claude with specific arguments claude-trace --run-with chat --model sonnet-3.5 # Show help claude-trace --help # Extract OAuth token claude-trace --extract-token ``` -------------------------------- ### Install Linux Dependencies Source: https://github.com/badlogic/lemmy/blob/main/apps/snap-happy/README.md Provides commands to install necessary screenshot utilities on Debian-based (Ubuntu) and Fedora-based (RHEL) Linux distributions. These are prerequisites for Snap Happy on Linux. ```bash # Ubuntu/Debian sudo apt install gnome-screenshot # Fedora/RHEL sudo dnf install gnome-screenshot ``` -------------------------------- ### Build Terminal UI with lemmy-tui in TypeScript Source: https://context7.com/badlogic/lemmy/llms.txt Illustrates how to create interactive terminal applications using the lemmy-tui library. It covers setting up the TUI manager, creating components like text displays and editors, handling user input, and managing the UI hierarchy. This example simulates AI responses. ```typescript import { TUI, Container, TextComponent, TextEditor, MarkdownComponent } from "@mariozechner/lemmy-tui"; // Create TUI manager const ui = new TUI(); // Create components const header = new TextComponent("AI Chat Application", { bottom: 1 }); const chatHistory = new Container(); const editor = new TextEditor(); // Handle submissions editor.onSubmit = (text: string) => { if (!text.trim()) return; // Add user message const userMsg = new MarkdownComponent(`**You:** ${text}`); chatHistory.addChild(userMsg); // Simulate AI response (in practice, use lemmy client) setTimeout(() => { const aiMsg = new MarkdownComponent(`**AI:** Response to "${text}"`); chatHistory.addChild(aiMsg); ui.requestRender(); }, 500); }; // Build UI hierarchy ui.addChild(header); ui.addChild(chatHistory); ui.addChild(editor); ui.setFocus(editor); // Start the UI ui.start(); // To stop: ui.stop(); ``` -------------------------------- ### Create Multi-Component Layout using TypeScript Source: https://github.com/badlogic/lemmy/blob/main/packages/lemmy-tui/README.md Demonstrates how to arrange multiple Lemmy TUI components (TextComponent, Container, TextEditor, MarkdownComponent) into a complex layout. This example shows a header, a main content area with a chat log and input, and a sidebar, illustrating layout management and component composition. ```typescript import { TUI, Container, TextComponent, TextEditor, MarkdownComponent } from "@mariozechner/lemmy-tui"; const ui = new TUI(); // Create layout containers const header = new TextComponent("📝 Advanced TUI Demo", { bottom: 1 }); const mainContent = new Container(); const sidebar = new Container(); const footer = new TextComponent("Press Ctrl+C to exit", { top: 1 }); // Sidebar content sidebar.addChild(new TextComponent("📁 Files:", { bottom: 1 })); sidebar.addChild(new TextComponent("- config.json")); sidebar.addChild(new TextComponent("- README.md")); sidebar.addChild(new TextComponent("- package.json")); // Main content area const chatArea = new Container(); const inputArea = new TextEditor(); // Add welcome message chatArea.addChild( new MarkdownComponent(` # Welcome to the TUI Demo This demonstrates multiple components working together: - **Header**: Static title with padding - **Sidebar**: File list (simulated) - **Chat Area**: Scrollable message history - **Input**: Interactive text editor - **Footer**: Status information Try typing a message and pressing Enter! `) ); inputArea.onSubmit = (text) => { if (text.trim()) { const message = new MarkdownComponent(` **${new Date().toLocaleTimeString()}:** ${text} `); chatArea.addChild(message); ui.requestRender(); } }; // Build layout mainContent.addChild(chatArea); mainContent.addChild(inputArea); ui.addChild(header); ui.addChild(mainContent); ui.addChild(footer); uis.setFocus(inputArea); // Configure debug logging uis.configureLogging({ enabled: true, level: "info", logFile: "tui-debug.log", }); uis.start(); ``` -------------------------------- ### Development Commands for lemmy-chat Source: https://github.com/badlogic/lemmy/blob/main/apps/lemmy-chat/README.md Provides essential commands for developing the lemmy-chat application, including starting a development server, building the project, and performing type checking. ```bash # Development mode npm run dev # Build npm run build # Type checking npm run typecheck ``` -------------------------------- ### Configure and Use snap-happy MCP Server (Bash & JSON) Source: https://context7.com/badlogic/lemmy/llms.txt A screenshot capture MCP server for AI assistants. It can be installed globally and added to Claude Code. Configuration can be done via environment variables or a JSON file. It also supports direct JSON-RPC testing for screenshotting and window listing. ```bash # Install globally npm install -g @mariozechner/snap-happy # Add to Claude Code claude mcp add snap-happy npx @mariozechner/snap-happy # Use in Claude echo "Take a screenshot" | claude -p echo "Show me the last screenshot" | claude -p ``` ```json // MCP client configuration { "mcpServers": { "snap-happy": { "command": "npx", "args": ["@mariozechner/snap-happy"], "env": { "SNAP_HAPPY_SCREENSHOT_PATH": "/Users/username/Screenshots" } } } } ``` ```bash # Test with JSON-RPC directly echo '{"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": "ListWindows", "arguments": {}}}' | npx @mariozechner/snap-happy echo '{"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": "TakeScreenshot", "arguments": {"windowId": 2}}}' | npx @mariozechner/snap-happy ``` -------------------------------- ### Advanced Chat Session with Lemmy CLI Source: https://github.com/badlogic/lemmy/blob/main/apps/lemmy-chat/README.md Illustrates how to start an advanced chat session with specific configurations like thinking enabled and custom token limits. The output provides detailed session information. ```bash # Start with thinking enabled and custom limits lemmy-chat chat -p anthropic -m claude-3-5-sonnet-20241022 --thinkingEnabled --maxOutputTokens 2000 # The session will show: # - Gray thinking text when the model reasons internally # - Token usage per message # - Running conversation cost # - Smooth terminal interface with proper line handling ``` -------------------------------- ### Development Commands for Lemmy Project Source: https://github.com/badlogic/lemmy/blob/main/packages/lemmy/README.md Provides essential npm commands for developing the Lemmy project. These include starting TypeScript compilation in watch mode, running tests, and performing type checking. Debugging is recommended using the Vitest extension in VS Code. ```bash npm run dev # Start TypeScript compilation in watch mode npm run test:run # Run tests npm run typecheck # Type checking ``` -------------------------------- ### Get Claude Absolute Path (TypeScript) Source: https://github.com/badlogic/lemmy/blob/main/todos/done/2025-07-16-21-31-31-issue-21-claude-absolute-path-analysis.md Retrieves the absolute path to the Claude CLI executable. It first attempts to find 'claude' in the system's PATH using `which`. If not found or if an error occurs, it falls back to checking a local installation path. This function is crucial for running Claude commands and extracting tokens within the claude-trace application. Dependencies include 'child_process', 'os', and 'path'. ```typescript function getClaudeAbsolutePath(): string { try { return require("child_process") .execSync("which claude", { encoding: "utf-8", }) .trim(); } catch (error) { const os = require("os"); const localClaudePath = path.join(os.homedir(), ".claude", "local", "node_modules", ".bin", "claude"); if (fs.existsSync(localClaudePath)) { return localClaudePath; } log(`❌ Claude CLI not found in PATH`, "red"); log(`❌ Also checked for local installation at: ${localClaudePath}`, "red"); log(`❌ Please install Claude Code CLI first`, "red"); process.exit(1); } } ``` -------------------------------- ### MCP Integration: Register and Use Puppeteer Server Source: https://github.com/badlogic/lemmy/blob/main/packages/lemmy-tools/README.md Demonstrates how to set up and use MCP (Model Context Protocol) servers, specifically the puppeteer server for browser automation. It involves creating an MCPRegistry, registering servers, and then adding the available MCP tools to the context. ```typescript import { MCPRegistry } from "@mariozechner/lemmy-tools/mcp"; const mcpRegistry = new MCPRegistry(); // Register MCP servers await mcpRegistry.registerServer("puppeteer", { command: "npx", args: ["@modelcontextprotocol/server-puppeteer"], timeout: 30000, }); // Add MCP tools to context const mcpTools = await mcpRegistry.getAvailableTools(); mcpTools.forEach((tool) => context.addTool(tool)); ``` -------------------------------- ### Usage: Add All Built-in Tools to Registry Source: https://github.com/badlogic/lemmy/blob/main/packages/lemmy-tools/README.md Shows how to obtain all built-in tools using `getBuiltinTools` and add them to a tool registry and the context. This pattern is useful for providing a comprehensive set of tools to the LLM. ```typescript import { getBuiltinTools, createToolRegistry } from "@mariozechner/lemmy-tools"; const registry = createToolRegistry(); const tools = getBuiltinTools(); tools.forEach((tool) => { registry.addTool(tool); context.addTool(tool); }); ``` -------------------------------- ### Install and Use claude-bridge CLI (Bash) Source: https://context7.com/badlogic/lemmy/llms.txt A command-line interface for using alternative LLM providers with Claude Code by transforming API requests. It allows setting API keys, discovering providers and models, and customizing API endpoints. Installation is done via npm. ```bash # Install globally npm install -g @mariozechner/claude-bridge # Set API keys export OPENAI_API_KEY=sk-... export GOOGLE_API_KEY=... # Discovery workflow claude-bridge # Show available providers claude-bridge openai # Show OpenAI models claude-bridge openai gpt-4o # Run Claude Code with GPT-4o # Custom API key per command claude-bridge openai gpt-4o --apiKey sk-... # Local Ollama claude-bridge openai llama3.2 --baseURL http://localhost:11434/v1 # OpenRouter claude-bridge openai gpt-4o --baseURL https://openrouter.ai/api/v1 --apiKey sk-or-... # Enable debug logging claude-bridge openai gpt-4o --debug # Trace Claude Code communication claude-bridge --trace -p "Hello world" # Pass arguments to Claude Code claude-bridge google gemini-2.5-pro-preview-05-06 --resume --continue ``` -------------------------------- ### Build Project Artifacts Source: https://github.com/badlogic/lemmy/blob/main/apps/claude-trace/README.md Builds the project, including the CLI, interceptor, and frontend web interface. Specific parts can also be built using 'npm run build:backend' or 'npm run build:frontend'. ```bash # Build everything npm run build # Or build specific parts npm run build:backend # CLI and interceptor npm run build:frontend # Web interface ``` -------------------------------- ### Error Handling Pattern in TypeScript Source: https://github.com/badlogic/lemmy/blob/main/packages/lemmy-tools/examples/README.md A common pattern for handling errors when using the lemmy-tools client. It includes try-catch blocks for unexpected errors and checks the result type for specific success or error handling. ```typescript try { const result = await client.ask(message, { context }); if (result.type === "success") { // Handle success } else { // Handle error console.log("Error:", result.error.message); } } catch (error) { // Handle unexpected errors } ``` -------------------------------- ### AutocompleteProvider Interface: Define Autocomplete Logic (TypeScript) Source: https://github.com/badlogic/lemmy/blob/main/packages/lemmy-tui/README.md The AutocompleteProvider interface defines the contract for custom autocomplete logic. It includes methods for getting suggestions based on current context and applying a selected completion to the text. ```typescript interface AutocompleteItem { value: string; label: string; description?: string; } interface AutocompleteProvider { getSuggestions( lines: string[], cursorLine: number, cursorCol: number, ): { items: AutocompleteItem[]; prefix: string; } | null; applyCompletion( lines: string[], cursorLine: number, cursorCol: number, item: AutocompleteItem, prefix: string, ): { lines: string[]; cursorLine: number; cursorCol: number; }; } ``` -------------------------------- ### Run Default and Specific Test Categories with npm Source: https://github.com/badlogic/lemmy/blob/main/apps/claude-bridge/test/README.md This section demonstrates how to execute tests using npm commands. It covers running all default tests (unit + core), specific test categories like unit, core, tools, providers, and comprehensive E2E tests, as well as running all available tests. ```bash # Run default tests (unit + core) npm test # Run specific test categories npm run test:unit # Fast unit tests npm run test:core # Core functionality only npm run test:tools # Tool integration tests npm run test:providers # Provider integration tests npm run test:comprehensive # All E2E tests # Run all tests npm run test:all ``` -------------------------------- ### Configure Snap Happy MCP Server Source: https://github.com/badlogic/lemmy/blob/main/apps/snap-happy/README.md Demonstrates how to configure the Snap Happy MCP server within an AI assistant's configuration. This includes specifying the command, arguments, and environment variables like the screenshot path. ```json { "mcpServers": { "snap-happy": { "command": "npx", "args": ["@mariozechner/snap-happy"], "env": { "SNAP_HAPPY_SCREENSHOT_PATH": "/Users/username/Screenshots" } } } } ``` -------------------------------- ### Start Interactive Chat with lemmy-chat Source: https://github.com/badlogic/lemmy/blob/main/apps/lemmy-chat/README.md Initiates an interactive chat session. Supports using saved defaults or specifying a provider and model explicitly. Features persistent context, streaming output, and token tracking. ```bash # Using saved defaults lemmy-chat chat # With specific provider and model lemmy-chat chat -p anthropic -m claude-3-5-sonnet-20241022 lemmy-chat chat -p openai -m gpt-4o lemmy-chat chat -p google -m gemini-1.5-pro ``` -------------------------------- ### Manual CLI Testing and Log Inspection (Bash) Source: https://github.com/badlogic/lemmy/blob/main/apps/claude-bridge/test/README.md Demonstrates how to manually test the CLI application and inspect generated log files using bash commands. This includes building the project, executing the CLI with specific arguments, and viewing the contents of log files. ```bash # Test CLI manually npm run build ./dist/cli.js openai gpt-4o -p "test prompt" # Check generated logs ls .claude-bridge/ cat .claude-bridge/requests-*.jsonl ``` -------------------------------- ### Test Snap Happy with Claude Code Source: https://github.com/badlogic/lemmy/blob/main/apps/snap-happy/README.md Examples of using Claude's code interpreter to interact with the Snap Happy MCP server. This includes taking a screenshot and requesting the last screenshot. ```bash # Take a screenshot echo "Take a screenshot" | claude -p # Show me the last screenshot echo "Show me the last screenshot" | claude -p ``` -------------------------------- ### Model Discovery Workflow for Lemmy CLI Source: https://github.com/badlogic/lemmy/blob/main/apps/lemmy-chat/README.md Shows how to discover and filter available language models using the Lemmy CLI. It includes finding cost-effective models with image support and exporting model data. ```bash # Find cost-effective models with image support lemmy-chat models --images --cheap # Get detailed Anthropic model information lemmy-chat models --provider anthropic # Export model data for scripts lemmy-chat models --json > models.json ``` -------------------------------- ### Create New Test Suite (TypeScript) Source: https://github.com/badlogic/lemmy/blob/main/apps/claude-bridge/test/README.md Illustrates the creation of a new test suite in TypeScript. This includes defining a suite with a name, an array of tests, and optional setup and teardown functions, which can then be added to a global testSuites array. ```typescript const newTestSuite: TestSuite = { name: "New Feature Suite", tests: myTests, setup: async () => { // optional setup }, teardown: async () => { // optional teardown }, }; // Add to testSuites array ``` -------------------------------- ### Emoji Usage for Console Logging (TypeScript) Source: https://github.com/badlogic/lemmy/blob/main/todos/done/2025-07-16-22-14-44-fix-log-file-output-message-analysis.md This example demonstrates the use of emojis in console log messages within the claude-trace application. Emojis are used to visually categorize messages such as errors, success, warnings, and informational content. ```typescript // Example usage in cli.ts for error messages log("❌ Error occurred: ...", "red"); // Example usage in cli.ts for success messages log("✅ Operation successful", "green"); // Example usage in cli.ts for startup message log("🚀 claude-trace started", "cyan"); // Example usage in interceptor.ts for browser operations console.log("🌐 Opening browser..."); ```