### Install and Configure Toxiproxy CLI Source: https://github.com/jeffallan/claude-skills/blob/main/skills/chaos-engineer/SKILL.md Installs the toxiproxy CLI and starts the server. Then, it creates a proxy for a downstream dependency and injects latency with jitter. ```bash # Install toxiproxy CLI brew install toxiproxy # macOS; use the binary release on Linux # Start toxiproxy server (runs alongside your service) toxiproxy-server & # Create a proxy for your downstream dependency toxiproxy-cli create -l 0.0.0.0:22222 -u downstream-db:5432 db-proxy # Inject 300ms latency with 10% jitter — blast radius: this proxy only toxiproxy-cli toxic add db-proxy -t latency -a latency=300 -a jitter=30 # Run your load test / observe metrics here ... # Remove the toxic to restore normal behaviour toxiproxy-cli toxic remove db-proxy -n latency_downstream ``` -------------------------------- ### Project Setup for User Dashboard Source: https://github.com/jeffallan/claude-skills/blob/main/skills/code-documenter/references/user-guides-tutorials.md Set up a new project for building a user dashboard. Initializes a new npm project and installs the SDK and React. ```bash mkdir user-dashboard cd user-dashboard npm init -y npm install @myapi/sdk react ``` -------------------------------- ### Install Flux CLI and Bootstrap Source: https://github.com/jeffallan/claude-skills/blob/main/skills/kubernetes-specialist/references/gitops.md Commands to install the Flux CLI using Homebrew and bootstrap a GitOps repository for a Kubernetes cluster. Includes checking prerequisites and examples for bootstrapping with GitHub and GitLab. ```bash # Install Flux CLI brew install fluxcd/tap/flux # Check prerequisites flux check --pre # Bootstrap Flux (GitHub) flux bootstrap github \ --owner=myorg \ --repository=fleet-infra \ --branch=main \ --path=clusters/production \ --personal # Bootstrap Flux (GitLab) flux bootstrap gitlab \ --owner=myorg \ --repository=fleet-infra \ --branch=main \ --path=clusters/production ``` -------------------------------- ### Ktor Server Testing Examples Source: https://github.com/jeffallan/claude-skills/blob/main/skills/kotlin-specialist/references/ktor-server.md Demonstrates how to test Ktor server endpoints for GET, POST, and authenticated routes using the testApplication utility. ```kotlin import io.ktor.client.request.* import io.ktor.client.statement.* import io.ktor.server.testing.* import kotlin.test.* class ApplicationTest { @Test fun testGetUsers() = testApplication { application { configureRouting() configureSerialization() } val response = client.get("/api/v1/users") assertEquals(HttpStatusCode.OK, response.status) } @Test fun testCreateUser() = testApplication { application { configureRouting() configureSerialization() } val response = client.post("/api/v1/users") { contentType(ContentType.Application.Json) setBody(CreateUserRequest("test@example.com", "Test User", "password123")) } assertEquals(HttpStatusCode.Created, response.status) } @Test fun testAuthenticatedRoute() = testApplication { application { configureAuth() configureRouting() } val token = generateToken("user123") val response = client.get("/api/v1/profile") { header(HttpHeaders.Authorization, "Bearer $token") } assertEquals(HttpStatusCode.OK, response.status) } } ``` -------------------------------- ### MySQL Index Hint Examples Source: https://github.com/jeffallan/claude-skills/blob/main/skills/sql-pro/references/optimization.md Provides examples of using index hints in MySQL to guide the optimizer towards specific indexes for query execution. ```sql -- MySQL: Index hints SELECT * FROM orders USE INDEX (idx_orders_customer_date) WHERE customer_id = 123; ``` ```sql SELECT * FROM orders FORCE INDEX (idx_orders_customer_date) WHERE customer_id = 123; ``` -------------------------------- ### Node.js SDK Setup Source: https://github.com/jeffallan/claude-skills/blob/main/skills/monitoring-expert/references/opentelemetry.md Configure the Node.js SDK with resource attributes, trace exporter, and auto-instrumentations. Ensure necessary packages are installed. ```typescript import { NodeSDK } from '@opentelemetry/sdk-node'; import { getNodeAutoInstrumentations } from '@opentelemetry/auto-instrumentations-node'; import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http'; import { Resource } from '@opentelemetry/resources'; import { SemanticResourceAttributes } from '@opentelemetry/semantic-conventions'; const sdk = new NodeSDK({ resource: new Resource({ [SemanticResourceAttributes.SERVICE_NAME]: 'my-service', [SemanticResourceAttributes.SERVICE_VERSION]: '1.0.0', }), traceExporter: new OTLPTraceExporter({ url: 'http://jaeger:4318/v1/traces', }), instrumentations: [getNodeAutoInstrumentations()], }); sdk.start(); ``` -------------------------------- ### Install Plugin from Marketplace Source: https://github.com/jeffallan/claude-skills/blob/main/QUICKSTART.md Use these commands to add the marketplace and install the plugin. Restart Claude Code after installation. ```bash # Add the marketplace /plugin marketplace add jeffallan/claude-skills # Install the plugin /plugin install fullstack-dev-skills@jeffallan # Restart Claude Code when prompted ``` -------------------------------- ### Init Containers Example Source: https://github.com/jeffallan/claude-skills/blob/main/skills/kubernetes-specialist/references/workloads.md Init containers run before the main application containers. They are useful for setup tasks like waiting for dependencies or performing schema migrations. ```yaml spec: initContainers: - name: wait-for-db image: busybox:latest command: ['sh', '-c'] args: - | until nc -z postgres-service 5432; do echo "Waiting for database..." sleep 2 done echo "Database is ready" - name: migrate-schema image: myregistry.io/migrations:latest command: ["/app/migrate", "up"] env: - name: DATABASE_URL valueFrom: secretKeyRef: name: db-secrets key: url containers: - name: app image: myregistry.io/app:latest ``` -------------------------------- ### Starting Next.js Production Server Source: https://github.com/jeffallan/claude-skills/blob/main/skills/nextjs-developer/references/deployment.md Build the Next.js application and start the production server using 'npm start'. For process management, use PM2 to start, manage, and save the Node.js process. ```bash # Build npm run build # Start production server npm start # With PM2 for process management pm2 start npm --name "nextjs" -- start pm2 startup pm2 save ``` -------------------------------- ### Multi-Module Repository (Monorepo) Setup Source: https://github.com/jeffallan/claude-skills/blob/main/skills/golang-pro/references/project-structure.md Structures a monorepo using `go.work` to manage multiple modules within a single repository. Includes example `go.work` content and commands. ```go monorepo/ ├── go.work # Workspace file ├── services/ │ ├── api/ │ │ ├── go.mod │ │ └── main.go │ └── worker/ │ ├── go.mod │ └── main.go └── shared/ └── models/ ├── go.mod └── user.go // go.work go 1.21 use ( ./services/api ./services/worker ./shared/models ) // Commands: // go work init ./services/api ./services/worker // go work use ./shared/models // go work sync ``` -------------------------------- ### Install Istio CLI and Default Profile Source: https://github.com/jeffallan/claude-skills/blob/main/skills/kubernetes-specialist/references/service-mesh.md Installs the Istio CLI and then installs Istio using the default profile. It also labels a namespace to enable sidecar injection and verifies the installation. ```bash # Install Istio CLI curl -L https://istio.io/downloadIstio | sh - export PATH=$PWD/istio-*/bin:$PATH # Install Istio with default profile istioctl install --set profile=default -y # Enable sidecar injection for namespace kubectl label namespace production istio-injection=enabled # Verify installation istioctl verify-install kubectl get pods -n istio-system ``` -------------------------------- ### Install Plugin from GitHub Source: https://github.com/jeffallan/claude-skills/blob/main/QUICKSTART.md Install the plugin directly from its GitHub repository. ```bash claude plugin install https://github.com/jeffallan/claude-skills ``` -------------------------------- ### Go Testable Examples Source: https://github.com/jeffallan/claude-skills/blob/main/skills/golang-pro/references/testing.md Write testable examples that serve as documentation and are verified by `go test`. These examples appear in `godoc` and can include assertions for expected output. ```go // Example tests that appear in godoc func ExampleAdd() { result := Add(2, 3) fmt.Println(result) // Output: 5 } ``` ```go func ExampleAdd_negative() { result := Add(-2, -3) fmt.Println(result) // Output: -5 } ``` ```go // Unordered output func ExampleKeys() { m := map[string]int{"a": 1, "b": 2, "c": 3} keys := Keys(m) for _, k := range keys { fmt.Println(k) } // Unordered output: // a // b // c } ``` -------------------------------- ### Install Fullstack Dev Skills Source: https://github.com/jeffallan/claude-skills/blob/main/README.md After installing the plugin, use this command to install the fullstack-dev-skills. ```bash /plugin install fullstack-dev-skills@jeffallan ``` -------------------------------- ### Install SDK Source: https://github.com/jeffallan/claude-skills/blob/main/skills/code-documenter/references/user-guides-tutorials.md Install the necessary SDK package using npm. Ensure Node.js 18+ is installed. ```bash npm install @myapi/sdk ``` -------------------------------- ### Create User SDK Example Source: https://github.com/jeffallan/claude-skills/blob/main/skills/code-documenter/references/interactive-api-docs.md Demonstrates how to create a user using the SDK in multiple programming languages. Requires API key for authentication and client initialization. ```python from myapi import Client client = Client(api_key="your_key") user = client.users.create( name="John Doe", email="john@example.com" ) print(user.id) ``` ```typescript import { Client } from '@myapi/sdk'; const client = new Client({ apiKey: 'your_key' }); const user = await client.users.create({ name: 'John Doe', email: 'john@example.com', }); console.log(user.id); ``` ```go import "github.com/myapi/sdk-go" client := sdk.NewClient("your_key") user, err := client.Users.Create(ctx, &sdk.CreateUserInput{ Name: "John Doe", Email: "john@example.com", }) if err != nil { log.Fatal(err) } fmt.Println(user.ID) ``` ```ruby require 'myapi' client = MyAPI::Client.new(api_key: 'your_key') user = client.users.create( name: 'John Doe', email: 'john@example.com' ) puts user.id ``` -------------------------------- ### GET - Retrieve Resources Example Source: https://github.com/jeffallan/claude-skills/blob/main/skills/api-designer/references/rest-patterns.md Example of a GET request to retrieve a specific user resource, including request headers and a success response. ```APIDOC **GET - Retrieve Resources** ```http GET /users/123 Accept: application/json Response: 200 OK { "id": 123, "name": "John Doe", "email": "john@example.com", "created_at": "2024-01-15T10:30:00Z" } ``` ``` -------------------------------- ### Basic Server Setup Source: https://github.com/jeffallan/claude-skills/blob/main/skills/mcp-developer/references/python-sdk.md Demonstrates how to set up a basic MCP server, define tools with input schemas, and handle tool calls. ```APIDOC ## Tool Definition and Handling ### Description Defines tools that the server can execute, including their input schemas and the logic for handling tool calls. ### Methods - `app.list_tools()`: Decorator to register a function that lists available tools. - `app.call_tool()`: Decorator to register a function that handles the execution of a specific tool. ### Tool Schema Example ```python from mcp.server import Server from mcp.types import Tool, TextContent, CallToolRequest from pydantic import BaseModel, Field import asyncio app = Server("example-server") class WeatherArgs(BaseModel): location: str = Field(..., description="City name or zip code") units: str = Field(default="celsius", pattern="^(celsius|fahrenheit)$") @app.list_tools() async def list_tools() -> list[Tool]: return [ Tool( name="get_weather", description="Get current weather for a location", inputSchema=WeatherArgs.model_json_schema(), ) ] @app.call_tool() async def call_tool(name: str, arguments: dict) -> list[TextContent]: if name == "get_weather": args = WeatherArgs(**arguments) weather_data = await fetch_weather(args.location, args.units) return [ TextContent( type="text", text=f"Weather in {args.location}: {weather_data['temp']}°{'C' if args.units == 'celsius' else 'F'}", ) ] raise ValueError(f"Unknown tool: {name}") async def main(): async with stdio_server() as (read_stream, write_stream): await app.run( read_stream, write_stream, app.create_initialization_options(), ) if __name__ == "__main__": asyncio.run(main()) ``` ``` -------------------------------- ### Install Fullstack Development Skills Source: https://github.com/jeffallan/claude-skills/blob/main/site/src/content/docs/index.mdx This command installs a specific package of full-stack development skills. Ensure you have the necessary permissions or environment setup for plugin installation. ```bash /plugin install fullstack-dev-skills@jeffallan ``` -------------------------------- ### GET - Retrieve Resources Example Source: https://github.com/jeffallan/claude-skills/blob/main/skills/api-designer/references/rest-patterns.md Demonstrates a GET request to retrieve a specific user resource and its expected JSON response. ```http GET /users/123 Accept: application/json Response: 200 OK { "id": 123, "name": "John Doe", "email": "john@example.com", "created_at": "2024-01-15T10:30:00Z" } ``` -------------------------------- ### Quick Reference: Development Setup and Teardown Source: https://github.com/jeffallan/claude-skills/blob/main/docs/local_skill_development.md A consolidated reference for setting up the symlink for development and tearing it down when finished. ```bash # Setup (one-time) CACHE=~/.claude/plugins/cache/// WORKDIR=/path/to/your/working/copy mv "$CACHE" "${CACHE}.bak" ln -s "$WORKDIR" "$CACHE" # Develop (repeat) # 1. Edit files in $WORKDIR # 2. Restart Claude Code # 3. Test # Teardown (when done) rm "$CACHE" mv "${CACHE}.bak" "$CACHE" ``` -------------------------------- ### Basic Server Setup and Tool Handling Source: https://github.com/jeffallan/claude-skills/blob/main/skills/mcp-developer/references/typescript-sdk.md Demonstrates how to set up a basic MCP server and handle requests for listing and calling tools. This includes defining tool schemas and implementing the logic for tool execution. ```APIDOC ## Basic Server Setup ### Description Sets up a new MCP server instance and configures request handlers for tool-related operations. ### Method `Server.setRequestHandler(schema, handler)` ### Parameters - **schema**: The Zod schema for the request (e.g., `ListToolsRequestSchema`, `CallToolRequestSchema`). - **handler**: An asynchronous function that processes the request and returns a response. ### Request Example (ListToolsRequestSchema) ```typescript server.setRequestHandler(ListToolsRequestSchema, async () => { return { tools: [ { name: "get_weather", description: "Get current weather for a location", inputSchema: { type: "object", properties: { location: { type: "string", description: "City name or zip code", }, units: { type: "string", enum: ["celsius", "fahrenheit"], default: "celsius", }, }, required: ["location"], }, }, ], }; }); ``` ### Request Example (CallToolRequestSchema) ```typescript server.setRequestHandler(CallToolRequestSchema, async (request) => { if (request.params.name === "get_weather") { const location = String(request.params.arguments?.location); const units = String(request.params.arguments?.units ?? "celsius"); // Your tool logic here const weatherData = await fetchWeather(location, units); return { content: [ { type: "text", text: `Weather in ${location}: ${weatherData.temp}°${units === "celsius" ? "C" : "F"}`, }, ], }; } throw new Error(`Unknown tool: ${request.params.name}`); }); ``` ### Response (ListToolsRequestSchema) Returns a list of available tools, each with a name, description, and input schema. ### Response (CallToolRequestSchema) Returns the result of the tool execution, typically as an array of content blocks. ``` -------------------------------- ### Context-Aware Activation Example (Backend) Source: https://github.com/jeffallan/claude-skills/blob/main/README.md Demonstrates how a backend development request activates specific skills and loads relevant references. ```bash # Backend Development "Implement JWT authentication in my NestJS API" → Activates: NestJS Expert → Loads: references/authentication.md ``` -------------------------------- ### Install Sealed Secrets Controller and CLI Source: https://github.com/jeffallan/claude-skills/blob/main/skills/kubernetes-specialist/references/gitops.md Provides commands to install the Sealed Secrets controller in Kubernetes and the kubeseal CLI tool. This setup is required for encrypting and decrypting Kubernetes secrets. ```bash # Install controller kubectl apply -f https://github.com/bitnami-labs/sealed-secrets/releases/download/v0.24.0/controller.yaml # Install kubeseal CLI brew install kubeseal ``` -------------------------------- ### Install and Run Pre-commit Hooks Source: https://github.com/jeffallan/claude-skills/blob/main/skills/terraform-engineer/references/testing.md Instructions for installing the pre-commit framework and its hooks, and how to run them manually. ```bash # Install pre-commit pip install pre-commit # Install hooks pre-commit install # Run manually pre-commit run -a ``` -------------------------------- ### Basic MCP Client Setup and Usage Source: https://github.com/jeffallan/claude-skills/blob/main/skills/mcp-developer/references/python-sdk.md Demonstrates how to set up a basic client to connect to an MCP server using stdio. This includes initializing the session, listing available tools, and calling a tool. ```python from mcp import ClientSession, StdioServerParameters from mcp.client.stdio import stdio_client import asyncio async def run_client(): server_params = StdioServerParameters( command="python", args=["server.py"], ) async with stdio_client(server_params) as (read, write): async with ClientSession(read, write) as session: # Initialize connection await session.initialize() # List available tools tools = await session.list_tools() print(f"Available tools: {[t.name for t in tools.tools]}") # Call a tool result = await session.call_tool( "get_weather", arguments={"location": "San Francisco"}, ) print(f"Result: {result.content}") if __name__ == "__main__": asyncio.run(run_client()) ``` -------------------------------- ### Migration Guide Markdown Structure Source: https://github.com/jeffallan/claude-skills/blob/main/skills/code-documenter/references/documentation-systems.md A markdown template for migration guides, including sections for breaking changes with code examples and tables comparing old and new methods, as well as a deprecation timeline. ```markdown # Migration Guide: v1 to v2 ## Breaking Changes ### Authentication **v1:** ```python client.authenticate(api_key) ``` **v2:** ```python client = Client(api_key=api_key) # Pass in constructor ``` ### Renamed Methods | v1 | v2 | Notes | |----|----|----- | | `get_user()` | `fetch_user()` | Async now | | `delete_user()` | `remove_user()` | Returns Promise | ## Deprecation Timeline - v1.x: Supported until Dec 2025 - v2.0: Released Jan 2025 - v2.1: Current (June 2025) ``` -------------------------------- ### Istio Installation Profiles Source: https://github.com/jeffallan/claude-skills/blob/main/skills/kubernetes-specialist/references/service-mesh.md Demonstrates how to install Istio using different profiles: minimal, default, demo, and production. The production profile includes resource tuning for proxies. ```bash # Minimal - only control plane istioctl install --set profile=minimal # Default - control plane + ingress gateway istioctl install --set profile=default # Demo - includes egress gateway, extra features istioctl install --set profile=demo # Production - tuned for production istioctl install --set profile=default \ --set values.global.proxy.resources.requests.cpu=100m \ --set values.global.proxy.resources.requests.memory=128Mi \ --set values.global.proxy.resources.limits.cpu=500m \ --set values.global.proxy.resources.limits.memory=256Mi ``` -------------------------------- ### SDK Installation and Configuration Source: https://github.com/jeffallan/claude-skills/blob/main/skills/code-documenter/references/interactive-api-docs.md Provides instructions for installing the SDK via npm and configuring the client with an API key, base URL, and timeout. Ensure environment variables are set for API keys. ```bash npm install @myapi/sdk ``` ```typescript import { Client } from '@myapi/sdk'; const client = new Client({ apiKey: process.env.API_KEY, baseUrl: 'https://api.example.com', // Optional timeout: 30000, // Optional, default 30s }); ``` -------------------------------- ### Few-Shot + CoT Prompt Example Source: https://github.com/jeffallan/claude-skills/blob/main/skills/prompt-engineer/references/prompt-patterns.md Demonstrates combining Few-Shot learning with Chain-of-Thought prompting for solving math word problems. It provides examples with step-by-step solutions to guide the model in solving new problems. ```plaintext Solve math word problems by showing your work. Example 1: Problem: If a train travels 60 mph for 2.5 hours, how far does it go? Solution: - Distance = Speed × Time - Distance = 60 mph × 2.5 hours - Distance = 150 miles Answer: 150 miles Example 2: Problem: A store has a 20% off sale. If an item costs $45, what's the sale price? Solution: - Discount = Original × Discount Rate - Discount = $45 × 0.20 = $9 - Sale Price = Original - Discount - Sale Price = $45 - $9 = $36 Answer: $36 Problem: {new_problem} Solution: ``` -------------------------------- ### Context-Aware Activation Example (Frontend) Source: https://github.com/jeffallan/claude-skills/blob/main/README.md Shows how a frontend development request triggers skill activation and reference loading. ```bash # Frontend Development "Build a React component with Server Components" → Activates: React Expert → Loads: references/server-components.md ``` -------------------------------- ### Few-Shot Prompting: Code Review Comments Example Source: https://github.com/jeffallan/claude-skills/blob/main/skills/prompt-engineer/references/prompt-patterns.md Effective for tasks requiring specific output formats or styles, like generating constructive code review comments. Provide clear examples to guide the model's response. ```text Generate a constructive code review comment for the given code issue. Example 1: Issue: Variable named 'x' in a function calculating total price Comment: Consider renaming 'x' to 'totalPrice' or 'priceSum' to improve readability. Descriptive variable names help future maintainers understand the code's intent without needing to trace through the logic. Example 2: Issue: SQL query built with string concatenation using user input Comment: This code is vulnerable to SQL injection attacks. Consider using parameterized queries or an ORM to safely handle user input. For example: `cursor.execute("SELECT * FROM users WHERE id = ?", (user_id,))` Example 3: Issue: Catch block that silently swallows exceptions Comment: Empty catch blocks can hide bugs and make debugging difficult. Consider logging the exception or, if the exception is truly expected, add a comment explaining why it's safe to ignore. Issue: {code_issue} Comment: ``` -------------------------------- ### Get Pod Resource Metrics Source: https://github.com/jeffallan/claude-skills/blob/main/skills/kubernetes-specialist/references/troubleshooting.md Retrieves current CPU and memory metrics for pods via the metrics API. Requires the metrics-server to be installed. ```bash kubectl get --raw /apis/metrics.k8s.io/v1beta1/pods ``` -------------------------------- ### Minimal API Setup in Program.cs Source: https://github.com/jeffallan/claude-skills/blob/main/skills/csharp-developer/references/aspnet-core.md Sets up a basic ASP.NET Core application using Minimal APIs. Includes service registration for Entity Framework Core, repositories, and application services, along with Swagger configuration. ```csharp // Program.cs using Microsoft.EntityFrameworkCore; var builder = WebApplication.CreateBuilder(args); // Services builder.Services.AddDbContext(options => options.UseSqlServer(builder.Configuration.GetConnectionString("Default"))); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); var app = builder.Build(); // Middleware pipeline if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); } app.UseHttpsRedirection(); app.UseAuthentication(); app.UseAuthorization(); // Map endpoints app.MapProductEndpoints(); app.Run(); ``` -------------------------------- ### Basic MCP Server Setup Source: https://github.com/jeffallan/claude-skills/blob/main/skills/mcp-developer/references/python-sdk.md Set up a basic MCP server with tool definitions and execution handlers. Requires importing necessary classes from mcp.server and mcp.types. ```python from mcp.server import Server from mcp.server.stdio import stdio_server from mcp.types import ( Tool, TextContent, CallToolRequest, ListToolsRequest, ) from pydantic import BaseModel, Field import asyncio # Create server instance app = Server("example-server") # Define tool input schema class WeatherArgs(BaseModel): location: str = Field(..., description="City name or zip code") units: str = Field(default="celsius", pattern="^(celsius|fahrenheit)$") # List available tools @app.list_tools() async def list_tools() -> list[Tool]: return [ Tool( name="get_weather", description="Get current weather for a location", inputSchema=WeatherArgs.model_json_schema(), ) ] # Handle tool execution @app.call_tool() async def call_tool(name: str, arguments: dict) -> list[TextContent]: if name == "get_weather": # Validate arguments args = WeatherArgs(**arguments) # Execute tool logic weather_data = await fetch_weather(args.location, args.units) return [ TextContent( type="text", text=f"Weather in {args.location}: {weather_data['temp']}°{ 'C' if args.units == 'celsius' else 'F' }", ) ] raise ValueError(f"Unknown tool: {name}") # Run server async def main(): async with stdio_server() as (read_stream, write_stream): await app.run( read_stream, write_stream, app.create_initialization_options(), ) if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Get Node Resource Metrics Source: https://github.com/jeffallan/claude-skills/blob/main/skills/kubernetes-specialist/references/troubleshooting.md Retrieves current CPU and memory metrics for nodes via the metrics API. Requires the metrics-server to be installed. ```bash kubectl get --raw /apis/metrics.k8s.io/v1beta1/nodes ``` -------------------------------- ### Basic Server Setup with TypeScript Source: https://github.com/jeffallan/claude-skills/blob/main/skills/mcp-developer/references/typescript-sdk.md Set up a basic MCP server instance, define its capabilities, and handle requests for listing tools and calling tools. This includes defining the input schema for a 'get_weather' tool. ```typescript import { Server } from "@modelcontextprotocol/sdk/server/index.js"; import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; import { CallToolRequestSchema, ListToolsRequestSchema, ListResourcesRequestSchema, ReadResourceRequestSchema, } from "@modelcontextprotocol/sdk/types.js"; import { z } from "zod"; // Create server instance const server = new Server( { name: "example-server", version: "1.0.0", }, { capabilities: { resources: {}, tools: {}, prompts: {}, }, } ); // Handle tools/list request server.setRequestHandler(ListToolsRequestSchema, async () => { return { tools: [ { name: "get_weather", description: "Get current weather for a location", inputSchema: { type: "object", properties: { location: { type: "string", description: "City name or zip code", }, units: { type: "string", enum: ["celsius", "fahrenheit"], default: "celsius", }, }, required: ["location"], }, }, ], }; }); // Handle tools/call request server.setRequestHandler(CallToolRequestSchema, async (request) => { if (request.params.name === "get_weather") { const location = String(request.params.arguments?.location); const units = String(request.params.arguments?.units ?? "celsius"); // Your tool logic here const weatherData = await fetchWeather(location, units); return { content: [ { type: "text", text: `Weather in ${location}: ${weatherData.temp}°${units === "celsius" ? "C" : "F"}`, }, ], }; } throw new Error(`Unknown tool: ${request.params.name}`); }); // Start server with stdio transport async function main() { const transport = new StdioServerTransport(); await server.connect(transport); console.error("MCP Server running on stdio"); } main().catch(console.error); ``` -------------------------------- ### PostgreSQL Configuration File Example Source: https://github.com/jeffallan/claude-skills/blob/main/skills/database-optimizer/references/postgresql-tuning.md An example of a production-optimized postgresql.conf file for a server with 16GB RAM, focusing on memory and WAL settings. ```ini # postgresql.conf - Production optimized for 16GB RAM server # Memory shared_buffers = 4GB effective_cache_size = 12GB work_mem = 40MB maintenance_work_mem = 2GB # WAL wal_buffers = 16MB checkpoint_completion_target = 0.9 max_wal_size = 2GB ``` -------------------------------- ### Few-shot Prompt for Sentiment Classification Source: https://github.com/jeffallan/claude-skills/blob/main/skills/prompt-engineer/SKILL.md An improved few-shot prompt for sentiment classification. Includes examples to guide the model towards more reliable outputs. ```text Classify the sentiment of the following review as Positive, Negative, or Neutral. Review: "The battery life is incredible, lasts all day." Sentiment: Positive Review: "Stopped working after two weeks. Very disappointed." Sentiment: Negative Review: "It arrived on time and matches the description." Sentiment: Neutral Review: {{review}} Sentiment: ``` -------------------------------- ### TDD Cycle: New Feature Example Source: https://github.com/jeffallan/claude-skills/blob/main/skills/test-master/references/tdd-iron-laws.md Demonstrates the RED-GREEN-REFACTOR cycle for developing a new feature, starting with a failing test and incrementally adding functionality. ```typescript // 1. RED: Write failing test for simplest behavior describe('UserValidator', () => { it('should reject empty email', () => { expect(validateEmail('')).toBe(false); }); }); // 2. GREEN: Implement minimal passing code function validateEmail(email: string): boolean { return email.length > 0; } // 3. RED: Add next failing test it('should reject email without @', () => { expect(validateEmail('invalid')).toBe(false); }); // 4. GREEN: Extend to pass both tests function validateEmail(email: string): boolean { return email.length > 0 && email.includes('@'); } // Continue cycle... ``` -------------------------------- ### Initialize and Start Software Timers Source: https://github.com/jeffallan/claude-skills/blob/main/skills/embedded-systems/references/rtos-patterns.md Demonstrates the creation and starting of one-shot and auto-reload software timers. Ensure timer handles are declared globally or appropriately scoped. ```c TimerHandle_t xWatchdogTimer; TimerHandle_t xBlinkTimer; void vWatchdogCallback(TimerHandle_t xTimer) { // Periodic watchdog check if (!SystemHealthCheck()) { SystemReset(); } } void vBlinkCallback(TimerHandle_t xTimer) { HAL_GPIO_TogglePin(LED_GPIO_Port, LED_Pin); } void InitTimers(void) { // One-shot timer xWatchdogTimer = xTimerCreate("Watchdog", pdMS_TO_TICKS(5000), pdTRUE, 0, vWatchdogCallback); // Auto-reload timer xBlinkTimer = xTimerCreate("Blink", pdMS_TO_TICKS(500), pdTRUE, 0, vBlinkCallback); // Start timers xTimerStart(xWatchdogTimer, 0); xTimerStart(xBlinkTimer, 0); } ``` -------------------------------- ### Chart Testing Tool (ct) Commands Source: https://github.com/jeffallan/claude-skills/blob/main/skills/kubernetes-specialist/references/helm-charts.md Commands for installing and using the `ct` tool for linting and testing Helm charts, including CI/CD integration examples. ```bash # Install chart-testing brew install chart-testing # Lint charts ct lint --config ct.yaml # Lint and install (CI/CD) ct lint-and-install --config ct.yaml # Test changed charts only ct lint-and-install --target-branch main --config ct.yaml ``` -------------------------------- ### Multi-Language SDK Examples Source: https://github.com/jeffallan/claude-skills/blob/main/skills/code-documenter/references/interactive-api-docs.md Provides examples of how to create a user using an SDK in multiple programming languages. ```APIDOC ## SDK Documentation Strategies ### Multi-Language Examples ```markdown # Create User ## Python ```python from myapi import Client client = Client(api_key="your_key") user = client.users.create( name="John Doe", email="john@example.com" ) print(user.id) ``` ## TypeScript ```typescript import { Client } from '@myapi/sdk'; const client = new Client({ apiKey: 'your_key' }); const user = await client.users.create({ name: 'John Doe', email: 'john@example.com', }); console.log(user.id); ``` ## Go ```go import "github.com/myapi/sdk-go" client := sdk.NewClient("your_key") user, err := client.Users.Create(ctx, &sdk.CreateUserInput{ Name: "John Doe", Email: "john@example.com", }) if err != nil { log.Fatal(err) } fmt.Println(user.ID) ``` ## Ruby ```ruby require 'myapi' client = MyAPI::Client.new(api_key: 'your_key') user = client.users.create( name: 'John Doe', email: 'john@example.com' ) puts user.id ``` ``` ``` -------------------------------- ### CLI Help Text Example Source: https://github.com/jeffallan/claude-skills/blob/main/skills/cli-developer/references/design-patterns.md Demonstrates the structure of help text for a CLI command, including usage, arguments, options, and examples. This format helps users understand how to interact with the command. ```bash USAGE mycli deploy [environment] [options] ARGUMENTS environment Target environment (development|staging|production) OPTIONS -c, --config Path to config file -f, --force Skip confirmation prompts -d, --dry-run Preview changes without executing -v, --verbose Show detailed output EXAMPLES # Deploy to production mycli deploy production # Preview staging deployment mycli deploy staging --dry-run # Use custom config mycli deploy --config ./custom.yml Learn more: https://docs.mycli.dev/deploy ``` -------------------------------- ### Node.js CLI with Commander Source: https://github.com/jeffallan/claude-skills/blob/main/skills/cli-developer/SKILL.md Basic setup for a Node.js CLI tool using the commander library. This example defines a simple command with an option and parses arguments. ```javascript #!/usr/bin/env node // npm install commander const { program } = require('commander'); program .name('mytool') .description('Example CLI') .version('1.0.0'); program .command('greet ') .description('Greet a user') .option('-l, --loud', 'uppercase the greeting') .action((name, opts) => { const msg = `Hello, ${name}!`; console.log(opts.loud ? msg.toUpperCase() : msg); }); program.parse(); ``` -------------------------------- ### Makefile Example for Build Automation Source: https://github.com/jeffallan/claude-skills/blob/main/skills/golang-pro/references/project-structure.md A basic Makefile demonstrating common targets for building, testing, linting, cleaning, and running Go projects. ```makefile # Makefile .PHONY: build test lint clean run ``` -------------------------------- ### Generate UUIDs with uuid-ossp Source: https://github.com/jeffallan/claude-skills/blob/main/skills/postgres-pro/references/extensions.md Install the uuid-ossp extension and use its functions to generate different versions of UUIDs. Includes an example of using UUIDs as primary keys in a table. ```sql CREATE EXTENSION IF NOT EXISTS "uuid-ossp"; -- Generate UUIDs SELECT uuid_generate_v1(); -- Time-based + MAC address SELECT uuid_generate_v4(); -- Random (most common) -- Use in tables CREATE TABLE users ( id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), email TEXT NOT NULL, created_at TIMESTAMPTZ DEFAULT NOW() ); -- Insert INSERT INTO users (email) VALUES ('user@example.com') RETURNING id; ``` -------------------------------- ### Go sync.Once for Initialization Source: https://github.com/jeffallan/claude-skills/blob/main/skills/golang-pro/references/concurrency.md Illustrates using sync.Once to ensure a configuration loading function is called exactly once, even if getConfig is called multiple times concurrently. Guarantees safe, one-time initialization. ```go // sync.Once for initialization type Service struct { once sync.Once config *Config } func (s *Service) getConfig() *Config { s.once.Do(func() { s.config = loadConfig() // Only called once }) return s.config } ``` -------------------------------- ### Git Bisect Manual Workflow Source: https://github.com/jeffallan/claude-skills/blob/main/skills/debugging-wizard/references/strategies.md Use Git Bisect to find the commit that introduced a bug. This example shows the manual steps of starting, marking good/bad commits, and resetting. ```bash # Start bisect git bisect start # Mark current commit as bad git bisect bad # Mark known good commit git bisect good v1.0.0 # Git checks out middle commit # Test and mark: git bisect good # or git bisect bad # Repeat until found # Git will say: "abc123 is the first bad commit" # End bisect git bisect reset ``` -------------------------------- ### Setuptools Configuration (`setup.py`) Source: https://github.com/jeffallan/claude-skills/blob/main/skills/python-pro/references/packaging.md Legacy configuration file for `setuptools`. Defines package metadata, find packages, Python version requirements, dependencies, and entry points. ```python # setup.py (if not using pyproject.toml) from setuptools import setup, find_packages setup( name="myproject", version="0.1.0", packages=find_packages(where="src"), package_dir={"" : "src"}, python_requires=">=3.11", install_requires=[ "requests>=2.31.0", "pydantic>=2.5.0", ], extras_require={ "dev": [ "pytest>=7.4.0", "mypy>=1.7.0", ], }, entry_points={ "console_scripts": [ "myproject=myproject.cli:main", ], }, ) ``` -------------------------------- ### Specific vs. Vague Feedback Example Source: https://github.com/jeffallan/claude-skills/blob/main/skills/code-reviewer/references/feedback-examples.md Illustrates how to provide specific, actionable feedback instead of vague criticism. Use this to guide reviewers towards clear and helpful comments. ```markdown BAD: "This is confusing" GOOD: "This function handles both validation and persistence. Consider splitting into `validateUser()` and `saveUser()` for single responsibility and easier testing." ``` -------------------------------- ### Basic Client Setup and Tool Interaction Source: https://github.com/jeffallan/claude-skills/blob/main/skills/mcp-developer/references/typescript-sdk.md Initialize an MCP client, establish a connection using a transport, list available tools, and call a tool with specified arguments. Ensure to use appropriate result schemas for validation. ```typescript import { Client } from "@modelcontextprotocol/sdk/client/index.js"; import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js"; const client = new Client( { name: "example-client", version: "1.0.0", }, { capabilities: {}, } ); // Connect to server const transport = new StdioClientTransport({ command: "node", args: ["./server.js"], }); await client.connect(transport); // List available tools const toolsResponse = await client.request( { method: "tools/list" }, ListToolsResultSchema ); console.log("Available tools:", toolsResponse.tools); // Call a tool const result = await client.request( { method: "tools/call", params: { name: "get_weather", arguments: { location: "San Francisco" }, }, }, CallToolResultSchema ); console.log("Result:", result.content); ``` -------------------------------- ### Monorepo Structure Example Source: https://github.com/jeffallan/claude-skills/blob/main/skills/fullstack-guardian/references/integration-patterns.md Illustrates a monorepo structure using a workspace setup, typically managed by tools like Lerna or Yarn Workspaces. Includes a sample `package.json` and `turbo.json` for Turborepo. ```plaintext workspace/ ├── packages/ │ ├── shared/ # Shared types, utils, schemas │ ├── backend/ # Node.js/Python backend │ ├── frontend/ # React/Vue frontend │ ├── mobile/ # React Native (optional) │ └── e2e-tests/ # End-to-end tests ├── package.json └── turbo.json # Turborepo config ``` ```json // package.json (workspace root) { "private": true, "workspaces": ["packages/*"], "scripts": { "dev": "turbo run dev", "build": "turbo run build", "test": "turbo run test" } } // turbo.json { "pipeline": { "build": { "dependsOn": ["^build"], "outputs": ["dist/**"] }, "dev": { "cache": false }, "test": { "dependsOn": ["build"], "outputs": [] } } } ``` -------------------------------- ### Get Cohere Query Embedding Source: https://github.com/jeffallan/claude-skills/blob/main/skills/rag-architect/references/embedding-models.md Generates an embedding for a search query. Use `input_type='search_query'` to optimize the embedding for matching against document embeddings. This example retrieves the first (and in this case, only) query embedding from the response. ```python # Query embeddings (for search) query_embedding = co.embed( texts=["how to install"], model="embed-english-v3.0", input_type="search_query", # Use for search queries ).embeddings[0] ``` -------------------------------- ### Ktor Server Application Setup Source: https://github.com/jeffallan/claude-skills/blob/main/skills/kotlin-specialist/references/ktor-server.md Sets up the Ktor server with Netty, configures the port and host, and calls various configuration functions for routing, serialization, authentication, and monitoring. ```kotlin import io.ktor.server.application.* import io.ktor.server.engine.* import io.ktor.server.netty.* import io.ktor.server.plugins.contentnegotiation.* import io.ktor.serialization.kotlinx.json.* import kotlinx.serialization.json.Json fun main() { embeddedServer(Netty, port = 8080, host = "0.0.0.0") { configureRouting() configureSerialization() configureAuth() configureMonitoring() }.start(wait = true) } ``` ```kotlin fun Application.configureSerialization() { install(ContentNegotiation) { json(Json { prettyPrint = true isLenient = true ignoreUnknownKeys = true }) } } ``` -------------------------------- ### Playwright Selector Priority Examples Source: https://github.com/jeffallan/claude-skills/blob/main/skills/playwright-expert/references/selectors-locators.md Demonstrates the recommended order of preference for Playwright selectors, starting with the most accessible and robust options like role-based selectors and moving to less preferred methods like CSS/XPath. ```typescript await page.getByRole('button', { name: 'Submit' }); await page.getByRole('textbox', { name: 'Email' }); await page.getByRole('link', { name: 'Home' }); await page.getByRole('heading', { level: 1 }); ``` ```typescript await page.getByLabel('Email address'); await page.getByPlaceholder('Enter your email'); ``` ```typescript await page.getByTestId('user-avatar'); await page.getByTestId('submit-button'); ``` ```typescript await page.getByText('Welcome back'); await page.getByText(/welcome/i); ``` ```typescript await page.locator('.submit-btn'); // Last resort await page.locator('#email-input'); ``` -------------------------------- ### Custom Hooks with flutter_hooks Source: https://github.com/jeffallan/claude-skills/blob/main/skills/flutter-expert/references/widget-patterns.md Utilize custom hooks from the flutter_hooks package to manage state and side effects within widgets. This example demonstrates `useState` for state management and `useEffect` for setup and cleanup logic. ```dart import 'package:flutter_hooks/flutter_hooks.dart'; class CounterWidget extends HookWidget { @override Widget build(BuildContext context) { final counter = useState(0); final controller = useTextEditingController(); useEffect(() => () { // Setup return () { // Cleanup }; }(), []); return Column( children: [ Text('Count: ${counter.value}'), ElevatedButton( onPressed: () => counter.value++, child: const Text('Increment'), ), ], ); } } ``` -------------------------------- ### Async Engine and Session Setup Source: https://github.com/jeffallan/claude-skills/blob/main/skills/fastapi-expert/references/async-sqlalchemy.md Configure the asynchronous database engine and session maker. Ensure settings.DATABASE_URL and settings.DEBUG are correctly defined. ```python from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession, async_sessionmaker from sqlalchemy.orm import DeclarativeBase engine = create_async_engine( settings.DATABASE_URL, echo=settings.DEBUG, pool_pre_ping=True, ) async_session = async_sessionmaker( engine, class_=AsyncSession, expire_on_commit=False, ) class Base(DeclarativeBase): pass ``` -------------------------------- ### ReAct + CoT Prompt Example Source: https://github.com/jeffallan/claude-skills/blob/main/skills/prompt-engineer/references/prompt-patterns.md Illustrates combining ReAct (Reasoning and Acting) with Chain-of-Thought (CoT) prompting. This pattern guides the model to break down a problem, reason through steps, and then formulate an action, such as a search query. ```plaintext Thought: Let me break this down step by step. First, I need to understand what information I'm looking for... [reasoning] Based on this analysis, I should search for... Action: search("specific query based on reasoning") ``` -------------------------------- ### Command Help Structure Source: https://github.com/jeffallan/claude-skills/blob/main/skills/cli-developer/references/ux-patterns.md Defines the standard structure for command-line help text, including USAGE, COMMANDS, OPTIONS, and EXAMPLES sections. It shows how to present global options and guide users to subcommand-specific help. ```text USAGE mycli [options] COMMANDS init Initialize a new project deploy Deploy to environment config Manage configuration plugins Manage plugins OPTIONS -h, --help Show help -v, --version Show version --config FILE Config file path Run 'mycli --help' for more information on a command. EXAMPLES # Initialize a new project mycli init my-app # Deploy to production mycli deploy production --dry-run Learn more: https://docs.mycli.dev ```