This is an example custom assistant that will help you complete the Python onboarding in VS Code. After trying it out, feel free to experiment with other blocks or create your own custom assistant.
relace
mistral
voyage
voyage
OpenAI
ollama
ollama
ollama
ollama
You have a short session-based memory, so you can use the memory tools (if present) to persist/access data between sessions. Use memory to store insights, notes, and context that is especially valuable for quick access.
- Follow Next.js patterns, use app router and correctly use server and client components.
- Use Tailwind CSS for styling.
- Use Shadcn UI for components.
- Use TanStack Query (react-query) for frontend data fetching.
- Use React Hook Form for form handling.
- Use Zod for validation.
- Use React Context for state management.
- Use Prisma for database access.
- Follow AirBnB style guide for code formatting.
- Use PascalCase when creating new React files. UserCard, not user-card.
- Use named exports when creating new react components.
- DO NOT TEACH ME HOW TO SET UP THE PROJECT, JUMP STRAIGHT TO WRITING COMPONENTS AND CODE.
- Optimize indexes to improve query execution speed.
- Avoid N+1 queries and suggest more efficient alternatives.
- Recommend normalization or denormalization strategies based on use cases.
- Implement transaction management where necessary to ensure data consistency.
- Suggest methods for monitoring database performance.
I am using the Next.js App Router v15.x.x
CRITICAL: In Next.js 15+, the `params` prop is a Promise and MUST be handled asynchronously. Follow these rules:
1. ALWAYS type params as Promise:
- Single param: Promise<{ slug: string }>
- Multiple params: Promise<{ categoryId: string; itemId: string }>
- Catch-all: Promise<{ slug: string[] }>
- Optional catch-all: Promise<{ slug?: string[] }>
2. ALWAYS use async/await pattern:
- Make component function async: export default async function MyPage({ params })
- Await params before accessing: const { slug } = await params;
- NEVER access params directly: params.slug is INCORRECT
3. Apply to ALL dynamic route files:
- Pages: app/[slug]/page.tsx
- Layouts: app/[slug]/layout.tsx
- Route handlers: app/api/[id]/route.ts
- All HTTP methods (GET, POST, PUT, DELETE, etc.)
4. Alternative: Use React's use() hook:
- Import: import { use } from 'react';
- Usage: const { slug } = use(params);
5. Proper error handling:
- Wrap in try/catch: try { const { slug } = await params; } catch { return <ErrorPage />; }
6. generateStaticParams should return objects matching param structure:
- [slug] → [{ slug: 'value' }]
- [categoryId]/[itemId] → [{ categoryId: 'cat', itemId: 'item' }]
7. FORBIDDEN patterns (will cause errors):
- const { slug } = params; // Synchronous access
- params.slug // Direct property access
- Non-async functions with param access
Remember: Synchronous access is deprecated in Next.js 15+ and will be removed.
### 🔄 Project Awareness & Context
- **Always read `PLANNING.md`** at the start of a new conversation to understand the project's architecture, goals, style, and constraints.
- **Check `TASK.md`** before starting a new task. If the task isn’t listed, add it with a brief description and today's date.
- **Use consistent naming conventions, file structure, and architecture patterns** as described in `PLANNING.md`.
### 🧱 Code Structure & Modularity
- **Never create a file longer than 500 lines of code.** If a file approaches this limit, refactor by splitting it into modules or helper files.
- **Organize code into clearly separated modules**, grouped by feature or responsibility.
- **Use clear, consistent imports** (prefer relative imports within packages).
### 🧪 Testing & Reliability
- **Always create Pytest unit tests for new features** (functions, classes, routes, etc).
- **After updating any logic**, check whether existing unit tests need to be updated. If so, do it.
- **Tests should live in a `/tests` folder** mirroring the main app structure.
- Include at least:
- 1 test for expected use
- 1 edge case
- 1 failure case
### ✅ Task Completion
- **Mark completed tasks in `TASK.md`** immediately after finishing them.
- Add new sub-tasks or TODOs discovered during development to `TASK.md` under a “Discovered During Work” section.
### 📎 Style & Conventions
- **Use Python** as the primary language.
- **Follow PEP8**, use type hints, and format with `black`.
- **Use `pydantic` for data validation**.
- Use `FastAPI` for APIs and `SQLAlchemy` or `SQLModel` for ORM if applicable.
- Write **docstrings for every function** using the Google style:
```python
def example():
"""
Brief summary.
Args:
param1 (type): Description.
Returns:
type: Description.
"""
```
### 📚 Documentation & Explainability
- **Update `README.md`** when new features are added, dependencies change, or setup steps are modified.
- **Comment non-obvious code** and ensure everything is understandable to a mid-level developer.
- When writing complex logic, **add an inline `# Reason:` comment** explaining the why, not just the what.
### 🧠 AI Behavior Rules
- **Never assume missing context. Ask questions if uncertain.**
- **Never hallucinate libraries or functions** – only use known, verified Python packages.
- **Always confirm file paths and module names** exist before referencing them in code or tests.
- **Never delete or overwrite existing code** unless explicitly instructed to or if part of a task from `TASK.md`.
- Always define explicit types for all props passed to custom or Shadcn/UI components. Utilize Zod schemas to validate complex prop structures, especially for data passed from server components or API routes. This ensures type safety at runtime and during development.
Example:
```typescript
// components/UserCard.tsx
import { z } from 'zod';
import { Card, CardHeader, CardTitle, CardDescription, CardContent } from "@/components/ui/card"; // Assuming Shadcn/UI path
const userCardPropsSchema = z.object({
userId: z.string().uuid(),
name: z.string().min(1),
email: z.string().email().optional(),
registrationDate: z.date(),
});
type UserCardProps = z.infer<typeof userCardPropsSchema>;
export const UserCard = ({ userId, name, email, registrationDate }: UserCardProps) => {
// Validate props at runtime (optional, primarily for data from external sources)
try {
userCardPropsSchema.parse({ userId, name, email, registrationDate });
} catch (error) {
console.error("Invalid UserCard props:", error);
return <p>Error loading user data.</p>;
}
return (
<Card>
<CardHeader>
<CardTitle>{name}</CardTitle>
{email && <CardDescription>{email}</CardDescription>}
</CardHeader>
<CardContent>
<p>User ID: {userId}</p>
<p>Registered: {registrationDate.toLocaleDateString()}</p>
</CardContent>
</Card>
);
};
```
rationale: Enhances code reliability and maintainability by catching type errors early and ensuring components receive the data they expect.
<!-- Sequential Thinking Workflow -->
<assistant>
<toolbox>
<mcp_server name="sequential-thinking"
role="workflow_controller"
execution="sequential-thinking"
description="Initiate the sequential-thinking MCP server">
<tool name="STEP" value="1">
<description>Gather context by reading the relevant file(s).</description>
<arguments>
<argument name="instructions" value="Seek proper context in the codebase to understand what is required. If you are unsure, ask the user." type="string" required="true"/>
<argument name="should_read_entire_file" type="boolean" default="true" required="false"/>
</arguments>
<result type="string" description="Context gathered from the file(s). Output can be passed to subsequent steps."/>
</tool>
<tool name="STEP" value="2">
<description>Generate code changes based on the gathered context (from STEP 1).</description>
<arguments>
<argument name="instructions" value="Generate the proper changes/corrections based on context from STEP 1." type="string" required="true"/>
<argument name="code_edit" type="object" required="true" description="Output: The proposed code modifications."/>
</arguments>
<result type="object" description="The generated code changes (code_edit object). Output can be passed to subsequent steps."/>
</tool>
<tool name="STEP" value="3">
<description>Review the generated changes (from STEP 2) and suggest improvements.</description>
<arguments>
<argument name="instructions" type="string" value="Review the changes applied in STEP 2 for gaps, correctness, and adherence to guidelines. Suggest improvements or identify any additional steps needed." required="true"/>
</arguments>
<result type="string" description="Review feedback, suggested improvements, or confirmation of completion. Final output of the workflow."/>
</tool>
</mcp_server>
</toolbox>
</assistant>
Create an API route with the following functionality.
Please review my Next.js code with a focus on security issues.
Use the below as a starting point, but consider any other potential issues
You do not need to address every single area below, only what is relevant to the user's code.
1. Data Exposure:
- Verify Server Components aren't passing full database objects to Client Components
- Check for sensitive data in props passed to 'use client' components
- Look for direct database queries outside a Data Access Layer
- Ensure environment variables (non NEXT_PUBLIC_) aren't exposed to client
2. Server Actions ('use server'):
- Confirm input validation on all parameters
- Verify user authentication/authorization checks
- Check for unencrypted sensitive data in .bind() calls
3. Route Safety:
- Validate dynamic route parameters ([params])
- Check custom route handlers (route.ts) for proper CSRF protection
- Review middleware.ts for security bypass possibilities
4. Data Access:
- Ensure parameterized queries for database operations
- Verify proper authorization checks in data fetching functions
- Look for sensitive data exposure in error messages
Key files to focus on: files with 'use client', 'use server', route.ts, middleware.ts, and data access functions.
Review this API route for security vulnerabilities. Ask questions about the context, data flow, and potential attack vectors. Be thorough in your investigation.
Create a client component with the following functionality. If writing this as a server component is not possible, explain why.
Create a new Next.js page based on the following description.
Your task is to analyze the user's code to help them understand it's current caching behavior, and mention any potential issues.
Be concise, only mentioning what is necessary.
Use the following as a starting point for your review:
1. Examine the four key caching mechanisms:
- Request Memoization in Server Components
- Data Cache behavior with fetch requests
- Full Route Cache (static vs dynamic rendering)
- Router Cache for client-side navigation
2. Look for and identify:
- Fetch configurations (cache, revalidate options)
- Dynamic route segments and generateStaticParams
- Route segment configs affecting caching
- Cache invalidation methods (revalidatePath, revalidateTag)
3. Highlight:
- Potential caching issues or anti-patterns
- Opportunities for optimization
- Unexpected dynamic rendering
- Unnecessary cache opt-outs
4. Provide clear explanations of:
- Current caching behavior
- Performance implications
- Recommended adjustments if needed
Lastly, point them to the following link to learn more: https://nextjs.org/docs/app/building-your-application/caching
Your task is to analyze the user's Next.js/TypeScript application to understand its current state management strategy and provide recommendations for optimization, simplification, or addressing potential issues.
Be concise, focusing on actionable insights and best practices.
Use the following points as a guide for your review:
1. Identify Current State Mechanisms:
- Client-side state (e.g., `useState`, `useReducer`) in Client Components.
- React Context API usage: Scope, purpose, provider structure, and potential overuse or performance bottlenecks.
- Third-party state management libraries (e.g., Zustand, Redux Toolkit, Jotai, Recoil): Identify the library, its configuration, store structure, and typical usage patterns.
- Server Components and props drilling as a means of state distribution from server to client.
- URL-based state (e.g., search parameters, dynamic route segments).
- Usage of `useSWR` or React Query for managing server state and caching on the client.
2. Analyze State Scope and Distribution:
- Is global state clearly distinguished from local component state?
- Are there instances of excessive prop-drilling that could be refactored (e.g., using Context, composition, or a global store)?
- How is server-side state managed and synchronized with the client? (e.g., via Server Actions, API routes with client-side fetching libraries).
- Is state collocated effectively with the components that use it?
3. Evaluate Complexity, Scalability, and Maintainability:
- Is the current state management setup overly complex for the application's actual needs?
- How well is the current strategy likely to scale as the application grows in features and complexity?
- Are there inconsistencies in how state is managed across different modules or features of the application?
- How easy is it to test components and logic that depend on the current state management setup?
4. Check for Common Issues and Anti-Patterns:
- Potential for excessive re-renders triggered by state updates (especially with Context or large global stores).
- Risks of stale state or data synchronization problems between client and server, or across different client-side stores.
- Over-reliance on global state for data that is inherently local or could be derived.
- Difficulties in debugging state changes or tracing data flow.
5. Provide Clear Recommendations:
- Suggest simplifications where appropriate (e.g., opting for simpler built-in React features if a complex library isn't fully leveraged).
- Recommend patterns for better state colocation, separation of concerns, or modular store design.
- Highlight opportunities to leverage Next.js App Router features (like Server Components, Server Actions, or route handler caching) to reduce client-side state complexity.
- If multiple state management solutions are in use, advise on potential consolidation or clearer boundaries and reasons for each.
- Suggest specific refactoring strategies for problematic patterns identified.
Lastly, encourage the user to consider the trade-offs of each approach (e.g., bundle size, learning curve, developer experience) and point them to relevant documentation for any libraries or patterns discussed. For Next.js specific patterns, refer to: https://nextjs.org/docs/app/building-your-application/managing-state
Your task is to review the user's Next.js/TypeScript codebase to identify opportunities for enhancing type safety, leveraging advanced TypeScript features, and improving overall code quality and maintainability through stricter and more expressive typing.
Focus on providing practical, actionable advice with specific examples where possible.
Consider the following areas in your review:
1. TypeScript Configuration (`tsconfig.json`):
- Verify the status of strict mode options (e.g., `strict: true`, or individual flags like `noImplicitAny`, `strictNullChecks`, `strictFunctionTypes`, `strictPropertyInitialization`, `noImplicitThis`, `useUnknownInCatchVariables`, `exactOptionalPropertyTypes`).
- Recommend enabling stricter options if not already active, explaining the benefits for early error detection and code clarity.
- Review module resolution settings (`paths`, `baseUrl`) and other compiler options for best practices in a Next.js context.
2. Type Definitions and Annotations:
- Identify pervasive use of `any` and suggest more specific types, `unknown` (with appropriate type guards), or generics.
- Look for missing type annotations for function parameters, return values, variables, and object properties where type inference might be insufficient or ambiguous.
- Evaluate the clarity, precision, and reusability of custom types, interfaces, and enums. Are they too broad, too narrow, or inconsistently defined?
- Check for consistency in type naming conventions (e.g., `T` for generics, `I` prefix for interfaces if that's a project convention).
3. Advanced TypeScript Feature Utilization:
- Identify opportunities to use utility types (e.g., `Partial<T>`, `Readonly<T>`, `Pick<T, K>`, `Omit<T, K>`, `ReturnType<F>`, `Parameters<F>`, `NonNullable<T>`) to create more precise and maintainable types without redundancy.
- Suggest the use of generics for creating flexible and reusable components, functions, and custom hooks.
- Look for complex conditional type logic or mapped types that could be simplified or where their application could significantly improve type safety (e.g., typing API response transformations).
- Assess the use of template literal types for more specific string typing (e.g., for event names, keys).
4. Props, State, and Context Typing:
- Ensure React component props (for both Client and Server Components) are well-typed, including `children` and event handlers.
- Verify types for `useState`, `useReducer` state and actions, and React Context values.
- For Server Actions, ensure arguments and return types are explicitly and accurately defined.
- Ensure types for route parameters (`params`), search parameters (`searchParams`) in Next.js pages/layouts are correctly defined and accessed.
5. Data Fetching, API Routes, and End-to-End Type Safety:
- Check types for API request bodies, query parameters, path parameters, and responses in Next.js API/Route Handlers.
- Ensure data fetched from external APIs or databases is properly typed upon retrieval and throughout its transformation pipeline.
- Review how types are shared or synchronized between the frontend (client components, server components) and the backend (API/Route Handlers, server actions), aiming for a single source of truth for data structures. Consider tRPC or similar solutions if appropriate.
6. Error Handling and Type Guards:
- Examine `try...catch` blocks. Is the `error` object typed as `unknown` (requiring type narrowing/guards) or `any`? Promote `unknown`.
- Suggest patterns for creating custom error types and using type guards or assertion functions for safer error handling.
7. Code Quality, Maintainability, and Tooling:
- Highlight areas where improved typing could prevent common runtime errors or make refactoring safer and easier.
- Discuss how stricter and more expressive typing can improve code readability and serve as documentation.
- Suggest leveraging ESLint rules for TypeScript (e.g., from `@typescript-eslint/eslint-plugin`) to automatically enforce stricter typing and best practices.
Provide specific code examples where possible to illustrate your recommendations. Encourage an incremental approach to adopting stricter typings to manage the refactoring effort. Point to official TypeScript documentation for further learning: https://www.typescriptlang.org/docs/handbook/intro.html
Your task is to assist in scaffolding the necessary files and boilerplate code for a new full-stack feature in a Next.js/TypeScript application, based on the user's description. The goal is to provide a solid starting point, adhering to Next.js (App Router preferred unless specified otherwise) best practices.
Before generating code, if the feature description is brief or ambiguous, ask clarifying questions about: - The core **functionality** and primary user interactions. - **Data requirements**: What data entities are involved? What are their properties? Where might this data be stored or fetched from (conceptually)? Is the data primarily read-only, or will it involve create, update, delete (CRUD) operations? - **Client-side vs. Server-side focus**: Will the feature heavily rely on client-side interactivity, server-side rendering/logic, or a balanced mix? - Any known **UI component libraries** or specific architectural patterns the user intends to use. - **State management considerations**: Any initial thoughts on how state related to this feature will be managed.
Once the requirements are sufficiently clear, propose and then (upon confirmation, or directly if requirements are clear) generate the following, organized by likely file paths:
1. **Type Definitions** (e.g., in `lib/types/featureName.ts` or `app/featureName/types.ts`):
* Define TypeScript interfaces or types for the main data entities and any complex objects related to the feature.
* Example: `interface Task { id: string; text: string; completed: boolean; createdAt: Date; }`
2. **API Route Handler(s)** (e.g., in `app/api/featureName/route.ts` or `app/api/featureName/[id]/route.ts`):
* Create basic handlers for relevant HTTP methods (GET, POST, PUT, DELETE) as appropriate for the feature's data manipulation needs.
* Include placeholder logic for data interaction (e.g., `// TODO: Implement database call`).
* Use the defined TypeScript types for request bodies, URL parameters, and response payloads.
* Implement basic request validation (e.g., checking for required fields).
* Provide JSDoc comments explaining each handler.
* Example for POST: `export async function POST(request: Request) { const data: Partial<Task> = await request.json(); // TODO: Validate data and save to DB; return NextResponse.json(newTask); }`
3. **Server Component(s) for Data Display/Logic** (e.g., in `app/featureName/components/FeatureDisplay.tsx` or directly in `app/featureName/page.tsx`):
* If the feature involves server-rendered data, create async Server Component(s) to fetch and prepare data.
* This component might call internal service functions or directly `Workspace` from your API routes.
* Example: `async function FeatureList() { const tasks = await fetch('/api/featureName').then(res => res.json()); return (<ul>{tasks.map(task => <li key={task.id}>{task.text}</li>)}</ul>); }`
4. **Client Component(s) for Interactivity** (e.g., in `app/featureName/components/FeatureForm.tsx`):
* Mark with `"use client";`.
* Include basic state management (`useState`, `useEffect`) for user inputs, UI state, etc.
* Implement functions to interact with the API routes (e.g., using `Workspace` to submit data or trigger actions).
* Handle form submissions, button clicks, and other user events.
* Example: A form to add a new task, with input fields and a submit handler that POSTs to `/api/featureName`.
5. **Main Page Route** (e.g., in `app/featureName/page.tsx`):
* Set up the primary page file that composes the Server and/or Client Components to present the feature to the user.
* This page should orchestrate the display of data and interactive elements.
6. **(Optional) Server Action(s)** (e.g., in `app/featureName/actions.ts`):
* If appropriate for mutations, define Server Action(s) using `"use server";`.
* Ensure inputs are validated and types are used.
* These can be called from Client Components or used in form submissions.
* Example: `export async function createTask(formData: FormData) { // ...logic to create task, revalidatePath('/'); }`
Guidelines for Generated Code: - Use placeholder comments (e.g., `// TODO: Implement actual data fetching/mutation`, `// TODO: Add robust error handling and user feedback`) where further implementation details are needed. - Follow Next.js App Router conventions unless the user specifies Pages Router. - Ensure generated TypeScript code is type-safe, utilizing the defined types consistently. - Provide clear context on where each file should be placed and brief instructions on how they connect. - Prioritize creating a coherent and functional set of interconnected files that provide a strong foundation for the user to build upon.
https://log-api.newrelic.com/log/v1
npx -y @executeautomation/playwright-mcp-server
npx -y @browsermcp/mcp@latest
npx -y @modelcontextprotocol/server-memory
npx -y @modelcontextprotocol/server-github
npx -y @modelcontextprotocol/server-filesystem ${{ secrets.ctan-dev/ctan-dev-next/anthropic/filesystem-mcp/PATH }}
npx -y @modelcontextprotocol/server-brave-search
npx -y tavily-mcp@0.1.4
docker run --rm -i mcp/sequentialthinking