Loading source
Pulling the file list, source metadata, and syntax-aware rendering for this listing.
Source from repo
DEPRECATED: Replaced by mcp-app-builder. Previously used to build ChatGPT apps with interactive React widgets via mcp-use.
Files
Skill
Size
Entrypoint
Format
Open file
Syntax-highlighted preview of this file as included in the skill package.
references/server/prompts.md
1# Prompts23Prompts are reusable message templates with parameters that help structure AI interactions.45**Use prompts for:** Code review templates, summarization patterns, translation templates, instruction templates67---89## Basic Prompt1011```typescript12import { MCPServer, text } from "mcp-use/server";13import { z } from "zod";1415const server = new MCPServer({16name: "my-server",17version: "1.0.0"18});1920server.prompt(21{22name: "code-review",23description: "Generate a code review prompt for given language",24schema: z.object({25language: z.string().describe("Programming language (e.g., 'TypeScript', 'Python')"),26focusArea: z.string().optional().describe("Specific area to focus on (e.g., 'security', 'performance')")27})28},29async ({ language, focusArea }) => {30const focus = focusArea ? ` with emphasis on ${focusArea}` : "";3132return text(33`Please review this ${language} code for best practices and potential issues${focus}.\n\n` +34`Consider:\n` +35`- Code quality and readability\n` +36`- Potential bugs or edge cases\n` +37`- Performance implications\n` +38`- Security vulnerabilities\n` +39`- Adherence to ${language} idioms`40);41}42);43```4445**Key points:**46- First argument: prompt configuration (name, description, schema)47- Second argument: async handler that returns prompt text48- Handler receives validated input matching schema49- Returns `text()` or `markdown()` helper with prompt content5051---5253## Prompt Definition5455### Name56Use kebab-case, descriptive names:57```typescript58✅ "code-review"59✅ "summarize-document"60✅ "translate-text"61✅ "explain-concept"6263❌ "prompt1"64❌ "review" // Too vague65```6667### Description68Explain what the prompt template does:69```typescript70✅ "Generate a code review prompt for any programming language with optional focus areas"71✅ "Create a translation prompt from source to target language"72✅ "Build a summarization prompt with configurable length and style"7374❌ "Code review" // Not descriptive enough75```7677### Schema78Define parameters with Zod, always use `.describe()`:7980```typescript81// ✅ Good82z.object({83language: z.string().describe("Programming language to review"),84focusArea: z.enum(["security", "performance", "style", "bugs"])85.optional()86.describe("Specific aspect to focus on"),87severity: z.enum(["all", "critical", "major"])88.default("all")89.describe("Minimum issue severity to report")90})9192// ❌ Bad - no descriptions93z.object({94language: z.string(),95focusArea: z.string().optional()96})97```9899---100101## Common Prompt Patterns102103### Code Review104105```typescript106server.prompt(107{108name: "code-review",109description: "Generate code review instructions",110schema: z.object({111language: z.string().describe("Programming language"),112style: z.enum(["strict", "moderate", "lenient"]).optional().describe("Review strictness")113})114},115async ({ language, style = "moderate" }) => {116const strictness = {117strict: "Be thorough and point out all issues, including minor style problems.",118moderate: "Focus on significant issues and best practices.",119lenient: "Only highlight critical bugs and security issues."120};121122return text(123`Review this ${language} code.\n\n` +124`${strictness[style]}\n\n` +125`Check for:\n` +126`- Correctness and potential bugs\n` +127`- Security vulnerabilities\n` +128`- Performance issues\n` +129`- Code clarity and maintainability`130);131}132);133```134135### Summarization136137```typescript138server.prompt(139{140name: "summarize",141description: "Create a summarization prompt",142schema: z.object({143length: z.enum(["brief", "medium", "detailed"]).describe("Summary length"),144format: z.enum(["paragraph", "bullets", "outline"]).describe("Output format")145})146},147async ({ length, format }) => {148const lengthGuide = {149brief: "2-3 sentences",150medium: "1 paragraph (5-7 sentences)",151detailed: "2-3 paragraphs with key points"152};153154const formatGuide = {155paragraph: "as a cohesive paragraph",156bullets: "as bullet points",157outline: "as a hierarchical outline"158};159160return text(161`Summarize the following content in ${lengthGuide[length]} ` +162`${formatGuide[format]}.\n\n` +163`Focus on the main points and key takeaways.`164);165}166);167```168169### Translation170171```typescript172server.prompt(173{174name: "translate",175description: "Generate translation instructions",176schema: z.object({177sourceLang: z.string().describe("Source language"),178targetLang: z.string().describe("Target language"),179tone: z.enum(["formal", "casual", "technical"]).optional().describe("Translation tone")180})181},182async ({ sourceLang, targetLang, tone = "formal" }) => {183return text(184`Translate the following text from ${sourceLang} to ${targetLang}.\n\n` +185`Maintain a ${tone} tone.\n` +186`Preserve the original meaning and nuance.\n` +187`Keep any technical terms or proper nouns intact unless they have established translations.`188);189}190);191```192193### Explanation194195```typescript196server.prompt(197{198name: "explain-concept",199description: "Generate explanation instructions for technical concepts",200schema: z.object({201concept: z.string().describe("Concept to explain"),202audience: z.enum(["beginner", "intermediate", "expert"]).describe("Target audience"),203includeExamples: z.boolean().default(true).describe("Include code examples")204})205},206async ({ concept, audience, includeExamples }) => {207const audienceLevel = {208beginner: "someone new to programming",209intermediate: "a developer with 1-2 years experience",210expert: "an experienced software engineer"211};212213let prompt = `Explain ${concept} to ${audienceLevel[audience]}.\n\n`;214215if (includeExamples) {216prompt += `Include practical code examples.\n`;217}218219prompt += `Use clear language and avoid unnecessary jargon.`;220221return text(prompt);222}223);224```225226---227228## Markdown Prompts229230For longer, structured prompts use `markdown()`:231232```typescript233import { markdown } from "mcp-use/server";234235server.prompt(236{237name: "api-design-review",238description: "Generate comprehensive API design review prompt",239schema: z.object({240apiType: z.enum(["REST", "GraphQL", "gRPC"]).describe("API type")241})242},243async ({ apiType }) => {244return markdown(`245# ${apiType} API Design Review246247Please review this ${apiType} API design for the following aspects:248249## 1. Design Quality250- RESTful principles (if REST)251- Resource naming and structure252- Consistency across endpoints253- Use of HTTP methods appropriately254255## 2. Security256- Authentication/authorization strategy257- Input validation258- Rate limiting considerations259- Sensitive data handling260261## 3. Performance262- Pagination strategy263- Caching headers264- Payload size optimization265- N+1 query prevention266267## 4. Developer Experience268- Clear, predictable patterns269- Good error messages270- Comprehensive examples271- Documentation clarity272273## 5. Versioning & Evolution274- Versioning strategy275- Backward compatibility276- Deprecation plan277278Please provide specific, actionable feedback with examples.279`);280}281);282```283284---285286## Dynamic Prompts287288Build prompts that adapt based on context:289290```typescript291server.prompt(292{293name: "debug-help",294description: "Generate debugging assistance prompt",295schema: z.object({296errorType: z.string().describe("Type of error (e.g., 'TypeError', 'NetworkError')"),297language: z.string().describe("Programming language"),298hasStackTrace: z.boolean().describe("Whether a stack trace is available")299})300},301async ({ errorType, language, hasStackTrace }) => {302let prompt = `Help me debug this ${errorType} in ${language}.\n\n`;303304if (hasStackTrace) {305prompt += `I have a stack trace. Please:\n`;306prompt += `1. Identify the root cause from the stack trace\n`;307prompt += `2. Explain why this error occurred\n`;308prompt += `3. Suggest fixes with code examples\n`;309} else {310prompt += `I don't have a full stack trace. Please:\n`;311prompt += `1. Ask questions to narrow down the issue\n`;312prompt += `2. Suggest common causes of ${errorType}\n`;313prompt += `3. Recommend debugging steps\n`;314}315316return text(prompt);317}318);319```320321---322323## Multi-Step Prompts324325Chain multiple prompts for complex workflows:326327```typescript328server.prompt(329{330name: "refactor-guide",331description: "Generate step-by-step refactoring instructions",332schema: z.object({333codeSmell: z.string().describe("Type of code smell to address"),334safetyLevel: z.enum(["aggressive", "moderate", "conservative"]).describe("Refactoring approach")335})336},337async ({ codeSmell, safetyLevel }) => {338const steps = {339aggressive: [340"Identify all instances of the code smell",341"Propose bold refactoring that may require significant changes",342"Show before/after code",343"List breaking changes"344],345moderate: [346"Identify the code smell",347"Propose incremental improvements",348"Show refactoring steps",349"Ensure backward compatibility"350],351conservative: [352"Identify the code smell",353"Propose minimal, safe changes",354"Preserve existing behavior exactly",355"Add tests before refactoring"356]357};358359return text(360`Refactor this code to address: ${codeSmell}\n\n` +361`Approach: ${safetyLevel}\n\n` +362`Follow these steps:\n` +363steps[safetyLevel].map((step, i) => `${i + 1}. ${step}`).join('\n')364);365}366);367```368369---370371## Prompt with Context372373Include environmental or system context:374375```typescript376server.prompt(377{378name: "optimize-for-runtime",379description: "Generate optimization suggestions for specific runtime",380schema: z.object({381runtime: z.enum(["node", "browser", "edge", "serverless"]).describe("Target runtime"),382metric: z.enum(["latency", "throughput", "memory", "cost"]).describe("Optimization goal")383})384},385async ({ runtime, metric }) => {386const runtimeContext = {387node: "Node.js server environment with access to filesystem and native modules",388browser: "Browser environment with limited resources and network constraints",389edge: "Edge runtime with fast cold starts but limited execution time",390serverless: "Serverless function with cold start concerns and pay-per-invocation pricing"391};392393return text(394`Optimize this code for ${runtime} runtime to improve ${metric}.\n\n` +395`Context: ${runtimeContext[runtime]}\n\n` +396`Consider:\n` +397`- ${metric === "latency" ? "Reduce response time" : ""}\n` +398`- ${metric === "throughput" ? "Increase requests/second" : ""}\n` +399`- ${metric === "memory" ? "Reduce memory footprint" : ""}\n` +400`- ${metric === "cost" ? "Minimize execution time and resources" : ""}\n\n` +401`Provide specific code changes with explanations.`402);403}404);405```406407---408409## Completion (Autocomplete)410411Add autocomplete suggestions to prompt arguments using `completable()`:412413```typescript414import { MCPServer, text, completable } from "mcp-use/server";415import { z } from "zod";416417// Static list of suggestions418server.prompt(419{420name: "code-review",421schema: z.object({422language: completable(z.string().describe("Programming language"), ["python", "typescript", "go", "rust"]),423code: z.string().describe("Code to review")424})425},426async ({ language, code }) => text(`Review this ${language} code...`)427);428```429430### Dynamic Completion431432Use a callback for suggestions that depend on context or external data:433434```typescript435server.prompt(436{437name: "analyze-project",438schema: z.object({439userId: completable(z.string().describe("User ID"), async (value) => {440const users = await fetchUsers();441return users.map(u => u.id).filter(id => id.startsWith(value));442}),443projectId: completable(z.string().describe("Project ID"), async (value, ctx) => {444// Use other argument values for contextual suggestions445const userId = ctx?.arguments?.userId;446const projects = await fetchProjects(userId);447return projects.map(p => p.id).filter(id => id.startsWith(value));448})449})450},451async ({ userId, projectId }) => text(`Analyzing project ${projectId}...`)452);453```454455**Key points:**456- `completable(schema, values)` — static list, prefix-matched automatically457- `completable(schema, callback)` — dynamic, receives `(value, ctx)` where `ctx.arguments` has other field values458- Works with `z.string()`, `z.number()`, and `z.enum()` schemas459- Clients request suggestions via MCP `completion/complete`460461---462463## Best Practices464465### 1. Clear Instructions466```typescript467✅ "Translate the following text from English to Spanish. Maintain formal tone."468❌ "Translate this."469```470471### 2. Structured Output472When you want structured responses, specify format:473```typescript474return text(475`Review this code and respond in the following format:\n\n` +476`## Issues Found\n` +477`- [Issue description]\n\n` +478`## Suggested Fixes\n` +479`- [Fix description with code]\n\n` +480`## Severity\n` +481`[Critical/Major/Minor]`482);483```484485### 3. Provide Context486Include relevant context in the prompt:487```typescript488return text(489`You are reviewing ${language} code for a ${projectType} project.\n` +490`Team follows ${styleGuide} style guide.\n\n` +491`Review the code below...`492);493```494495### 4. Be Specific496```typescript497✅ "Summarize in 3-5 bullet points, each under 20 words"498❌ "Summarize briefly"499```500501---502503## Prompts vs Tools504505**Use a prompt when:**506- ✅ Providing instructions to the AI507- ✅ Creating reusable message templates508- ✅ Structuring AI interactions509- ✅ No backend logic needed510511**Use a tool when:**512- ✅ Executing backend actions513- ✅ Calling APIs or databases514- ✅ Returning computed data515- ✅ Has side effects516517**Example:**518```typescript519// ✅ Prompt - Just instructions520server.prompt(521{ name: "review-code", ... },522async ({ language }) => text(`Review this ${language} code...`)523);524525// ✅ Tool - Executes action526server.tool(527{ name: "run-linter", schema: z.object({ file: z.string() }) },528async ({ file }) => {529const results = await runLinter(file);530return object(results);531}532);533```534535---536537## Complete Example538539```typescript540import { MCPServer, text, markdown } from "mcp-use/server";541import { z } from "zod";542543const server = new MCPServer({544name: "prompt-server",545version: "1.0.0"546});547548// Simple text prompt549server.prompt(550{551name: "explain-error",552description: "Generate error explanation prompt",553schema: z.object({554errorMessage: z.string().describe("The error message"),555context: z.string().optional().describe("Additional context")556})557},558async ({ errorMessage, context }) => {559let prompt = `Explain this error message in simple terms:\n"${errorMessage}"\n\n`;560561if (context) {562prompt += `Context: ${context}\n\n`;563}564565prompt += `Provide:\n1. What it means\n2. Common causes\n3. How to fix it`;566567return text(prompt);568}569);570571// Structured markdown prompt572server.prompt(573{574name: "pr-review",575description: "Generate pull request review checklist",576schema: z.object({577type: z.enum(["feature", "bugfix", "refactor"]).describe("PR type")578})579},580async ({ type }) => {581return markdown(`582# Pull Request Review Checklist (${type})583584## Code Quality585- [ ] Code follows project style guide586- [ ] No unnecessary code duplication587- [ ] Functions are small and focused588- [ ] Variable names are clear and descriptive589590## Testing591- [ ] ${type === "feature" ? "New tests added for new functionality" : ""}592- [ ] ${type === "bugfix" ? "Regression test added" : ""}593- [ ] All tests pass594- [ ] Edge cases covered595596## Documentation597- [ ] Code comments where necessary598- [ ] README updated if needed599- [ ] API docs updated600601## ${type === "feature" ? "Feature Specific" : type === "bugfix" ? "Bug Fix Specific" : "Refactor Specific"}602${type === "feature" ? "- [ ] Feature flag implemented if needed\n- [ ] Backward compatible" : ""}603${type === "bugfix" ? "- [ ] Root cause identified\n- [ ] Fix verified in production-like environment" : ""}604${type === "refactor" ? "- [ ] No behavior changes\n- [ ] Performance impact assessed" : ""}605`);606}607);608609server.listen();610```611612---613614## Next Steps615616- **Format responses** → [response-helpers.md](response-helpers.md)617- **Create tools** → [tools.md](tools.md)618- **See examples** → [../patterns/common-patterns.md](../patterns/common-patterns.md)619