Master the
Copilot CLI
Ecosystem
Explore agents, skills, prompts, MCP integrations, and CLI workflows. Your interactive guide to GitHub Copilot's command-line interface.
Agent Explorer
Discover the agents that power Copilot CLI — their tools, skills, and how to use them.
Skills Explorer
Explore the specialized skills agents use — from code generation to security auditing.
Prompt Library
45+ battle-tested prompts organized by category. Copy, customize, and use in your CLI workflow.
40 prompts found
Scaffold a Full-Stack App
Code GenerationGenerate a complete full-stack application with frontend, backend, and database setup.
Create a full-stack TypeScript application with a React frontend (Vite), Express API backend, and PostgreSQL database. Include authentication with JWT, CRUD operations for a "tasks" resource, and proper error handling. Set up the project structure with separate client/server directories.
Create a REST API Endpoint
Code GenerationGenerate a RESTful API endpoint with validation, error handling, and documentation.
Create a REST API endpoint for managing user profiles. Include GET (list/detail), POST, PUT, and DELETE operations. Add input validation with Zod, proper HTTP status codes, and TypeScript types.
Generate React Component
Code GenerationCreate a production-ready React component with TypeScript, tests, and stories.
Create a reusable DataTable React component with TypeScript. Support sortable columns, pagination, row selection, and search filtering. Use TailwindCSS for styling. Include prop types and a usage example.
CLI Tool Generator
Code GenerationBuild a Node.js command-line tool with argument parsing and interactive prompts.
Create a Node.js CLI tool using Commander.js for managing database migrations. Include commands: create, up, down, status. Add interactive confirmation prompts for destructive operations and colored output.
WebSocket Server
Code GenerationGenerate a WebSocket server with rooms, authentication, and reconnection handling.
Create a WebSocket server using ws library in Node.js. Implement rooms/channels, JWT authentication on connection, heartbeat/ping mechanism, graceful reconnection handling, and typed message protocols.
Convert Callbacks to Async/Await
RefactoringRefactor callback-based code to use modern async/await patterns.
Refactor all callback-based functions in this file to use async/await. Preserve error handling, add proper try/catch blocks, and ensure all edge cases are covered. Maintain backward compatibility.
Extract Reusable Module
RefactoringBreak a large file into smaller, reusable modules with clean interfaces.
This file is over 500 lines. Analyze it and extract logical groups into separate modules. Create clean public interfaces (exports) for each module. Update all imports. Ensure no circular dependencies.
Apply Design Pattern
RefactoringRefactor code to implement a specific design pattern for better extensibility.
Refactor the payment processing code to use the Strategy pattern. Each payment method (credit card, PayPal, crypto) should be a separate strategy. Include a factory for creating strategies and maintain the existing interface.
Improve Type Safety
RefactoringAdd strict TypeScript types, eliminating any types and adding proper generics.
Audit this codebase for type safety issues. Replace all `any` types with proper types. Add generics where applicable. Enable strict null checks and fix all resulting errors. Add discriminated unions for state management.
Optimize Performance
RefactoringRefactor code for better runtime performance — memoization, lazy loading, reduced allocations.
Analyze this React application for performance issues. Add React.memo, useMemo, and useCallback where beneficial. Implement code splitting with lazy/Suspense. Optimize re-renders. Add virtualization for long lists.
Fix Failing Tests
DebuggingAnalyze test failures, identify root causes, and apply fixes.
Run the test suite, analyze all failing tests, identify the root cause of each failure, and fix them. Explain what was wrong and why the fix works. Do not modify the test expectations unless they are clearly wrong.
Debug Memory Leak
DebuggingIdentify and fix memory leaks in a Node.js application.
Analyze this Node.js application for memory leaks. Check for: unclosed connections, event listener accumulation, large object retention, missing cleanup in intervals/timeouts, and circular references. Fix all issues found.
Debug API Error
DebuggingTrace an API error from the HTTP response back to the root cause in the codebase.
I'm getting a 500 Internal Server Error on POST /api/orders. Trace the request flow from the route handler through middleware, service layer, and database queries. Find the root cause and fix it.
Fix Race Condition
DebuggingIdentify and resolve race conditions in async code.
There's a race condition causing intermittent failures in the order processing system. Analyze all concurrent operations, identify where race conditions can occur, and implement proper synchronization (locks, queues, or atomic operations).
Debug Build Failure
DebuggingDiagnose and fix build/compilation errors in a project.
The build is failing with TypeScript compilation errors. Analyze the build output, identify all errors, determine if they are type errors, missing dependencies, or config issues, and fix everything so the build passes.
Design Microservices Split
ArchitectureAnalyze a monolith and propose a microservices decomposition strategy.
Analyze this monolithic application. Identify bounded contexts, propose service boundaries, define API contracts between services, suggest a communication strategy (sync/async), and create a migration plan from monolith to microservices.
Design Database Schema
ArchitectureDesign a normalized database schema for a domain with relationships and indexes.
Design a PostgreSQL database schema for an e-commerce platform. Include tables for users, products, categories, orders, order items, payments, reviews, and inventory. Add proper foreign keys, indexes for common queries, and constraints.
API Design Review
ArchitectureReview and improve an API design for consistency, usability, and RESTful best practices.
Review the API design in this project. Check for RESTful conventions, consistent naming, proper HTTP methods, pagination patterns, error response formats, versioning strategy, and rate limiting. Suggest improvements.
Event-Driven Architecture
ArchitectureDesign an event-driven system with publishers, subscribers, and event schemas.
Design an event-driven architecture for the notification system. Define event types, create event schemas, implement publisher/subscriber patterns, add dead letter queue handling, and ensure idempotent event processing.
CI/CD Pipeline
DevOpsCreate a complete CI/CD pipeline with testing, building, and deployment stages.
Create a GitHub Actions CI/CD pipeline for a Node.js application. Include: lint, test (with coverage), build, security scan, Docker build, push to registry, and deploy to staging on PR merge, production on release.
Dockerfile Optimization
DevOpsCreate a production-optimized multi-stage Dockerfile.
Create an optimized multi-stage Dockerfile for this Node.js application. Include: build stage, production stage with minimal image, non-root user, health check, proper cache layers, .dockerignore, and security hardening.
Infrastructure as Code
DevOpsGenerate Terraform/IaC templates for cloud infrastructure.
Create Terraform configurations for deploying this application to AWS. Include: VPC, ECS Fargate cluster, RDS PostgreSQL, ElastiCache Redis, Application Load Balancer, CloudWatch monitoring, and IAM roles with least-privilege.
Monitoring & Alerting
DevOpsSet up application monitoring, logging, and alerting.
Set up monitoring for this application. Add structured logging with correlation IDs, health check endpoints, metrics collection (request latency, error rate, memory usage), and alerting rules for SLA breaches.
K8s Deployment
DevOpsCreate Kubernetes manifests for containerized deployment.
Create Kubernetes manifests for this application. Include: Deployment with rolling update, Service, Ingress with TLS, ConfigMap, Secrets, HPA for autoscaling, PodDisruptionBudget, and resource limits.
Database Migration
Data EngineeringCreate database migration scripts with rollback support.
Create database migration scripts for adding a multi-tenant architecture. Add tenant_id to all tables, create row-level security policies, update indexes, and include both up and down migrations with data preservation.
Query Optimization
Data EngineeringAnalyze and optimize slow database queries.
Analyze the database queries in this project. Identify slow queries, add missing indexes, rewrite inefficient joins, add proper pagination, and implement query result caching where appropriate.
ETL Pipeline
Data EngineeringCreate an ETL pipeline for data ingestion and transformation.
Create an ETL pipeline using Node.js that: extracts data from a REST API, transforms it (clean, validate, normalize), and loads it into PostgreSQL. Include error handling, retry logic, incremental processing, and logging.
AI Agent Workflow
AI/MLBuild an AI agent with tool calling and multi-step reasoning.
Create an AI agent using the OpenAI API that can: search the web, read files, execute code, and answer questions. Implement a tool-calling loop with proper error handling, context management, and conversation history.
RAG Pipeline
AI/MLBuild a Retrieval Augmented Generation pipeline for document Q&A.
Create a RAG pipeline for answering questions about documentation. Include: document chunking, embedding generation, vector store (using pgvector), semantic search retrieval, prompt construction with context, and response generation.
Prompt Engineering System
AI/MLCreate a prompt management system with templates and versioning.
Build a prompt template system with: variable interpolation, version tracking, A/B testing support, output validation, and logging. Include templates for common tasks (summarization, extraction, classification).
Unit Test Suite
TestingGenerate comprehensive unit tests with edge cases and mocks.
Write unit tests for all exported functions in this module. Use Vitest with TypeScript. Include: happy path, edge cases, error scenarios, boundary values, and mock external dependencies. Aim for >90% coverage.
E2E Test Scenarios
TestingCreate end-to-end tests for critical user flows.
Write E2E tests using Playwright for the critical user flows: signup, login, create order, view order history, and checkout. Include: page objects, test fixtures, visual regression checks, and CI configuration.
API Integration Tests
TestingCreate API integration tests with database setup/teardown.
Write API integration tests for all endpoints. Include: test database setup with migrations, seed data fixtures, request/response validation, auth token handling, cleanup after each test, and parallel execution support.
Comprehensive README
DocumentationGenerate a production-quality README with all essential sections.
Generate a comprehensive README.md for this project. Include: project description, features list, architecture overview, prerequisites, installation steps, configuration guide, usage examples, API reference, contributing guidelines, and license.
API Documentation
DocumentationGenerate OpenAPI/Swagger documentation from code.
Generate OpenAPI 3.0 documentation for all API endpoints. Include: path descriptions, request/response schemas, error codes, authentication requirements, example payloads, and write it as an openapi.yaml file.
Architecture Decision Record
DocumentationDocument an architecture decision with context, options, and rationale.
Create an Architecture Decision Record (ADR) for [decision]. Include: context, decision drivers, considered options with pros/cons, decision outcome, consequences, and compliance requirements.
OWASP Security Audit
SecurityAudit code against OWASP Top 10 vulnerabilities.
Audit this codebase against the OWASP Top 10. Check for: injection flaws, broken authentication, sensitive data exposure, XXE, broken access control, security misconfiguration, XSS, insecure deserialization, known vulnerabilities, and insufficient logging.
Auth Implementation Review
SecurityReview authentication and authorization implementation for security gaps.
Review the authentication and authorization system. Check: password hashing (bcrypt/argon2), JWT implementation (expiry, refresh, revocation), RBAC/ABAC enforcement, session management, CSRF protection, and OAuth flows.
Dependency Vulnerability Scan
SecurityScan and fix known vulnerabilities in project dependencies.
Scan all project dependencies for known vulnerabilities. Check npm audit results, identify critical/high severity issues, and update or replace vulnerable packages. Ensure updates don't break existing functionality.
Input Sanitization
SecurityAdd input validation and sanitization across all entry points.
Review all user input entry points (API endpoints, form handlers, URL parameters). Add proper input validation, sanitization, and parameterized queries. Prevent SQL injection, XSS, command injection, and path traversal.
CLI Commands & Playground
Every slash command, flag, mode, and environment variable — with examples you can copy.
/planActivate plan mode for structured task planning. Copilot asks clarifying questions before generating code.
/modelSwitch between available AI models. Shows model list with request multipliers.
/fleetExecute tasks in parallel across multiple subagents or models.
/delegateHand off the current session to GitHub's server-side Copilot agent. Creates a branch and PR.
/diffReview all code changes made in the current session.
/agentList, select, or manage custom agents defined in AGENTS.md or .copilot/agents.yml.
/skillsList and manage agent skills — specialized task abilities and instructions.
/mcpView, configure, and manage MCP (Model Context Protocol) servers.
/resumeContinue long-running work from a previous session.
/compactManually compress conversation context to free up token space.
/contextView detailed token usage breakdown for the current session.
/allow-allGrant Copilot full permissions for the current session — no more approval prompts.
/yoloAlias for /allow-all — run with full permissions. Use with caution.
/experimentalAccess preview and experimental features not yet generally available.
/changelogView the latest feature updates and changes to Copilot CLI.
/feedbackSubmit feedback — bug report, feature request, or private survey.
-p, --promptRun in programmatic mode with a single prompt. Completes the task and exits.
--modelSpecify which AI model to use for the session.
--allow-all-toolsGrant all tool permissions upfront — no approval prompts during execution.
--allow-toolAllow a specific tool or command without requiring approval.
--deny-toolBlock a specific tool from being used, even if other permissions are granted.
Interactive ModeLaunch with `copilot` for a chat-like terminal interface. Supports slash commands, plan mode, and iterative workflows.
Programmatic ModeLaunch with `copilot -p` for headless execution. Completes the task and exits. Ideal for scripts and automation.
Plan ModeToggle with Shift+Tab or /plan. Copilot creates a structured plan before executing, asking clarifying questions first.
COPILOT_PROVIDER_BASE_URLSet a custom API endpoint for the model provider.
COPILOT_PROVIDER_TYPESpecify the provider type: openai, azure, or anthropic.
COPILOT_PROVIDER_API_KEYAPI key for authentication with a custom model provider.
COPILOT_MODELSpecify the model name (required when using custom provider).
COPILOT_OFFLINESet to "true" for offline mode — disables telemetry and web-based tools.
MCP Integrations
Extend Copilot CLI with Model Context Protocol servers — connect databases, browsers, and custom tools.
GitHub MCP Server
Native GitHub integration providing access to issues, pull requests, code search, branches, labels, and repository management directly from the CLI.
Available Tools
# Built-in — no configuration needed.
# Available automatically when authenticated with GitHub.
# Access via: copilot /mcp
# Mention in prompts:
copilot -p "Use GitHub MCP to list all open issues labeled 'bug'"# List open bugs
copilot -p "Find all open issues labeled 'bug' and summarize them"
# Create a PR from CLI
copilot -p "Create a pull request for the current branch with a description of all changes"
# Search code across repos
copilot -p "Search the codebase for deprecated API usage"CLI Quick Start Guide
From installation to mastery — everything you need to get started with Copilot CLI.
1Installation
2Authentication
3Usage Modes
Interactive Mode
Launch a chat-like session with full slash command support.
# Start interactive session
copilot
# With a specific model
copilot --model claude-sonnet-4Programmatic Mode
Execute a single prompt and exit. Great for scripts and CI.
# Run single prompt
copilot -p "Fix all lint errors"
# With auto-approved tools
copilot -p "Run tests" --allow-all-tools4Key Concepts
Trust Boundary
Copilot operates within the current working directory. It can only access files in the trusted project root and its subdirectories.
Auto-Compaction
When conversation context reaches 95%, Copilot automatically compresses history while preserving key information. Use /compact manually when needed.
Tool Permissions
Every tool invocation requires approval by default. Use --allow-tool or --allow-all-tools to pre-approve. Use --deny-tool to block specific tools.
5Customization
# Project Instructions
## Tech Stack
- TypeScript, React, Express
- PostgreSQL with Prisma ORM
## Conventions
- Use functional components
- Prefer async/await over callbacks
- All new code must have tests
- Follow existing naming conventions# Custom Agent: Frontend Lead
## Role
You are a senior frontend engineer
specializing in React and TypeScript.
## Tools
- read_file, write_file, shell
## Instructions
- Use React 19 features
- Follow atomic design
- Add Storybook stories for componentsAgent Flow Visualizer
See how prompts flow through agents, skills, and tools to produce results.
How Copilot CLI traces a bug from user prompt to fixed code.
Hover over a node to see details
Best Practices
Expert tips for getting the most out of Copilot CLI — prompt engineering, performance, and workflow optimization.
Be Explicit and Specific
The more context you give, the better the output. Specify language, framework, patterns, and constraints.
- →Include the programming language and framework explicitly
- →Specify file paths when referring to existing code
- →Mention coding conventions and style preferences
- →Define input/output expectations clearly
- →State constraints: "without breaking existing tests" or "maintaining backward compatibility"
Break Complex Tasks into Steps
Large tasks get better results when decomposed. Use plan mode or sequential prompts.
- →Use /plan mode for complex multi-step tasks
- →Start with analysis: "Analyze this file and identify issues"
- →Then act: "Fix the issues you identified"
- →Queue follow-up messages while Copilot is working
- →Use iterative refinement: start broad, then narrow down
Use Templates and Patterns
Structured prompts produce structured output. Use consistent prompt patterns for repeatable results.
- →Pattern: "Create a [thing] that [does what] using [technology] with [constraints]"
- →Pattern: "Review [target] for [criteria]. Suggest fixes for [priority issues]"
- →Pattern: "Refactor [code] to use [pattern]. Maintain [invariants]"
- →Save effective prompts for reuse across projects
- →Combine prompts with CLI flags for automation
Provide Examples and Context
Show Copilot what you want with examples. Reference existing code patterns in your project.
- →"Follow the same pattern as src/routes/users.ts"
- →"Here's an example of the expected output format: ..."
- →"Use the same error handling approach as the auth module"
- →Reference config files: "Use the ESLint rules in .eslintrc"
- →Mention existing tests as patterns: "Follow the test style in __tests__/"
Start in the Right Directory
Always launch Copilot from your project root. It uses the working directory as its trust boundary.
- →cd to your project root before running `copilot`
- →Copilot can only read/modify files within the trusted directory
- →Use git repositories — Copilot leverages git context
- →Run from the directory with your package.json / pyproject.toml
- →For monorepos, cd to the specific package directory for focused context
Master Tool Permissions
Understand and use the tool permission system to balance speed and safety.
- →--allow-all-tools for trusted automation tasks
- →--allow-tool='shell(npm test)' to auto-approve specific commands
- →--allow-tool='write' to skip file write approvals
- →--deny-tool='shell(rm)' to block dangerous operations even with --allow-all-tools
- →Use /allow-all during interactive sessions when you trust the operations
Use Programmatic Mode for Automation
Combine -p flag with tool permissions for scriptable CLI workflows.
- →copilot -p "prompt" for single-shot execution
- →Chain with shell: copilot -p "Fix lint errors" && npm run lint
- →Use in CI: copilot -p "Generate changelog" --allow-all-tools
- →Pipe input: echo "explain this" | copilot -p -
- →Combine with --model for specific model selection
Manage Context Effectively
Keep conversations focused. Use /compact when context grows large.
- →Use /compact to compress context without losing key information
- →Use /context to check current token usage
- →Start new sessions for unrelated tasks
- →Use /resume to continue previous work in new sessions
- →Copilot auto-compacts at 95% token limit
Scope Your Prompts Tightly
Smaller, focused prompts execute faster and produce better results than broad ones.
- →Target specific files: "Fix the bug in src/utils/auth.ts"
- →Avoid "fix everything" — instead "fix the 3 TypeScript errors in this file"
- →Use file paths to narrow the search scope
- →One task per prompt in programmatic mode
- →Batch related changes but keep them in the same domain
Choose the Right Model
Different models have different strengths. Use /model to switch based on the task.
- →Use faster models for simple tasks (explanations, small edits)
- →Use advanced models for complex architecture and multi-file refactoring
- →Check request multipliers with /model — higher multiplier = more quota used
- →Use /fleet to try multiple models in parallel for important decisions
- →Set COPILOT_MODEL env var to default to your preferred model
Leverage Custom Instructions
Pre-configure Copilot with project-specific knowledge to reduce prompt size and improve accuracy.
- →Create .copilot/instructions.md with project conventions
- →Define coding style, architecture patterns, and tech stack
- →Add common gotchas and project-specific rules
- →Use AGENTS.md for role-specific agents
- →Copilot Memory automatically learns your patterns over time
Workflow Templates
End-to-end automation scripts for common development workflows — ready to customize and run.
Refactor Legacy Codebase
Systematically modernize a legacy codebase — update patterns, fix anti-patterns, and improve maintainability.
Workflow Steps
Prompt
Analyze this codebase for legacy patterns. Create a prioritized modernization plan, then execute it step by step. Start with the highest-impact, lowest-risk changes. Run tests after each change.
Generate Microservice
Scaffold a complete microservice with API, database, Docker, and CI/CD.
Workflow Steps
Prompt
Create a Node.js microservice with TypeScript, Express, PostgreSQL (Prisma ORM), JWT authentication, input validation with Zod, structured logging, health checks, Dockerfile, docker-compose, GitHub Actions CI/CD, and OpenAPI docs.
Fix CI Pipeline
Diagnose and fix a failing CI/CD pipeline — build errors, test failures, and deployment issues.
Workflow Steps
Prompt
The CI pipeline is failing. Analyze the GitHub Actions workflow, check the recent logs, identify what changed, and fix the issues. Ensure the pipeline passes for both PR checks and main branch deployment.
Analyze Repository
Get a comprehensive understanding of an unfamiliar codebase — architecture, patterns, and entry points.
Workflow Steps
Prompt
Analyze this repository comprehensively. Explain: the tech stack, project structure, architecture patterns, main entry points, data flow, key modules, testing approach, and deployment setup. Then list the top 5 areas for improvement.
Add Feature with Tests
Implement a new feature following TDD — write tests first, then implementation.
Workflow Steps
Prompt
Implement [feature description] using TDD. First write failing tests that define the expected behavior, then implement the feature to pass all tests. Add both unit and integration tests. Update the README with the new feature.
Security Hardening
Comprehensive security audit and hardening of an application.
Workflow Steps
Prompt
Perform a comprehensive security audit: scan dependencies, check OWASP Top 10, review auth, find hardcoded secrets, validate inputs, and set up security headers. Fix all critical and high severity issues.
API Migration (v1 → v2)
Plan and execute an API version migration with backward compatibility.
Workflow Steps
Prompt
Plan an API migration from v1 to v2. Document all v1 endpoints, design improved v2 endpoints, implement them alongside v1 with deprecation warnings, create a migration guide, and add tests to verify both versions work.
Performance Optimization
Profile, identify bottlenecks, and optimize application performance.
Workflow Steps
Prompt
Analyze this application for performance bottlenecks. Check: slow database queries, missing indexes, N+1 queries, unnecessary re-renders, large bundle size, missing caching. Fix the top issues and add performance monitoring.