Compare commits

...

9 Commits

Author SHA1 Message Date
shadcn
21686d7e83 chore: add changesets 2025-08-26 12:14:11 +04:00
shadcn
bc56bb6022 docs: restructure mcp docs 2025-08-26 12:13:50 +04:00
shadcn
d44ab7ffa4 feat(shadcn): add mcp init command 2025-08-25 22:49:37 +04:00
shadcn
8c143c5de2 docs(www): update registry docs 2025-08-25 16:21:40 +04:00
shadcn
a4ba91ab44 Merge branch 'main' into shadcn/docs-registry 2025-08-25 14:14:19 +04:00
shadcn
200d3aba60 fix 2025-08-13 19:03:24 +04:00
shadcn
fd44aead8e docs(www): add cli command to docs 2025-08-13 18:15:40 +04:00
shadcn
cc564974c6 fix 2025-08-13 18:07:50 +04:00
shadcn
f72d0cf509 docs(www): namespaced registries 2025-08-13 17:53:26 +04:00
19 changed files with 2260 additions and 81 deletions

View File

@@ -0,0 +1,5 @@
---
"shadcn": major
---
add mcp init command

View File

@@ -193,7 +193,7 @@ export default async function Page(props: {
)}
</div>
</div>
<div className="sticky top-[calc(var(--header-height)+1px)] z-30 ml-auto hidden h-[calc(100svh-var(--header-height)-var(--footer-height))] w-72 flex-col gap-4 overflow-hidden overscroll-none pb-8 xl:flex">
<div className="sticky top-[calc(var(--header-height)+1px)] z-30 ml-auto hidden h-[calc(100svh-var(--footer-height)+2rem)] w-72 flex-col gap-4 overflow-hidden overscroll-none pb-8 xl:flex">
<div className="h-(--top-spacing) shrink-0" />
{/* @ts-expect-error - revisit fumadocs types. */}
{doc.toc?.length ? (

View File

@@ -6,8 +6,8 @@ import { Badge } from "@/registry/new-york-v4/ui/badge"
export function Announcement() {
return (
<Badge asChild variant="secondary" className="rounded-full">
<Link href="/docs/components/calendar">
New Calendar Component <ArrowRightIcon />
<Link href="/docs/registry/namespace">
Introducing Namespaced Registries <ArrowRightIcon />
</Link>
</Badge>
)

View File

@@ -15,6 +15,24 @@ import {
SidebarMenuItem,
} from "@/registry/new-york-v4/ui/sidebar"
const TOP_LEVEL_SECTIONS = [
{ name: "Get Started", href: "/docs" },
{
name: "Components",
href: "/docs/components",
},
{
name: "Registry",
href: "/docs/registry",
},
{
name: "MCP Server",
href: "/docs/mcp",
},
]
const EXCLUDED_SECTIONS = ["installation", "dark-mode"]
const EXCLUDED_PAGES = ["/docs"]
export function DocsSidebar({
tree,
...props
@@ -23,40 +41,79 @@ export function DocsSidebar({
return (
<Sidebar
className="sticky top-[calc(var(--header-height)+1px)] z-30 hidden h-[calc(100svh-var(--header-height)-var(--footer-height))] bg-transparent lg:flex"
className="sticky top-[calc(var(--header-height)+1px)] z-30 hidden h-[calc(100svh-var(--footer-height)+2rem)] bg-transparent lg:flex"
collapsible="none"
{...props}
>
<SidebarContent className="no-scrollbar px-2 pb-12">
<SidebarContent className="no-scrollbar overflow-x-hidden px-2 pb-12">
<div className="h-(--top-spacing) shrink-0" />
{tree.children.map((item) => (
<SidebarGroup key={item.$id}>
<SidebarGroupLabel className="text-muted-foreground font-medium">
{item.name}
</SidebarGroupLabel>
<SidebarGroupContent>
{item.type === "folder" && (
<SidebarMenu className="gap-0.5">
{item.children.map((item) => {
return (
item.type === "page" && (
<SidebarMenuItem key={item.url}>
<SidebarMenuButton
asChild
isActive={item.url === pathname}
className="data-[active=true]:bg-accent data-[active=true]:border-accent 3xl:fixed:w-full 3xl:fixed:max-w-48 relative h-[30px] w-fit overflow-visible border border-transparent text-[0.8rem] font-medium after:absolute after:inset-x-0 after:-inset-y-1 after:z-0 after:rounded-md"
>
<Link href={item.url}>{item.name}</Link>
</SidebarMenuButton>
</SidebarMenuItem>
<SidebarGroup>
<SidebarGroupLabel className="text-muted-foreground font-medium">
Sections
</SidebarGroupLabel>
<SidebarGroupContent>
<SidebarMenu>
{TOP_LEVEL_SECTIONS.map(({ name, href }) => {
return (
<SidebarMenuItem key={name}>
<SidebarMenuButton
asChild
isActive={
href === "/docs"
? pathname === href
: pathname.startsWith(href)
}
className="data-[active=true]:bg-accent data-[active=true]:border-accent 3xl:fixed:w-full 3xl:fixed:max-w-48 relative h-[30px] w-fit overflow-visible border border-transparent text-[0.8rem] font-medium after:absolute after:inset-x-0 after:-inset-y-1 after:z-0 after:rounded-md"
>
<Link href={href}>
<span className="absolute inset-0 flex w-(--sidebar-width) bg-transparent" />
{name}
</Link>
</SidebarMenuButton>
</SidebarMenuItem>
)
})}
</SidebarMenu>
</SidebarGroupContent>
</SidebarGroup>
{tree.children.map((item) => {
if (EXCLUDED_SECTIONS.includes(item.$id ?? "")) {
return null
}
return (
<SidebarGroup key={item.$id}>
<SidebarGroupLabel className="text-muted-foreground font-medium">
{item.name}
</SidebarGroupLabel>
<SidebarGroupContent>
{item.type === "folder" && (
<SidebarMenu className="gap-0.5">
{item.children.map((item) => {
return (
item.type === "page" &&
!EXCLUDED_PAGES.includes(item.url) && (
<SidebarMenuItem key={item.url}>
<SidebarMenuButton
asChild
isActive={item.url === pathname}
className="data-[active=true]:bg-accent data-[active=true]:border-accent 3xl:fixed:w-full 3xl:fixed:max-w-48 relative h-[30px] w-fit overflow-visible border border-transparent text-[0.8rem] font-medium after:absolute after:inset-x-0 after:-inset-y-1 after:z-0 after:rounded-md"
>
<Link href={item.url}>
<span className="absolute inset-0 flex w-(--sidebar-width) bg-transparent" />
{item.name}
</Link>
</SidebarMenuButton>
</SidebarMenuItem>
)
)
)
})}
</SidebarMenu>
)}
</SidebarGroupContent>
</SidebarGroup>
))}
})}
</SidebarMenu>
)}
</SidebarGroupContent>
</SidebarGroup>
)
})}
</SidebarContent>
</Sidebar>
)

View File

@@ -13,6 +13,22 @@ import {
PopoverTrigger,
} from "@/registry/new-york-v4/ui/popover"
const TOP_LEVEL_SECTIONS = [
{ name: "Get Started", href: "/docs" },
{
name: "Components",
href: "/docs/components",
},
{
name: "Registry",
href: "/docs/registry",
},
{
name: "MCP Server",
href: "/docs/mcp",
},
]
export function MobileNav({
tree,
items,
@@ -79,6 +95,18 @@ export function MobileNav({
))}
</div>
</div>
<div className="flex flex-col gap-4">
<div className="text-muted-foreground text-sm font-medium">
Sections
</div>
<div className="flex flex-col gap-3">
{TOP_LEVEL_SECTIONS.map(({ name, href }) => (
<MobileLink key={name} href={href} onOpenChange={setOpen}>
{name}
</MobileLink>
))}
</div>
</div>
<div className="flex flex-col gap-8">
{tree?.children?.map((group, index) => {
if (group.type === "folder") {

View File

@@ -210,3 +210,93 @@ Import alias for `hooks` such as `use-media-query` or `use-toast`.
}
}
```
## registries
Configure multiple resource registries for your project. This allows you to install components, libraries, utilities, and other resources from various sources including private registries.
See the <Link href="/docs/registry/namespace">Namespaced Registries</Link> documentation for detailed information.
### Basic Configuration
Configure registries with URL templates:
```json title="components.json"
{
"registries": {
"@v0": "https://v0.dev/chat/b/{name}",
"@acme": "https://registry.acme.com/{name}.json",
"@internal": "https://internal.company.com/{name}.json"
}
}
```
The `{name}` placeholder is replaced with the resource name when installing.
### Advanced Configuration with Authentication
For private registries that require authentication:
```json title="components.json"
{
"registries": {
"@private": {
"url": "https://api.company.com/registry/{name}.json",
"headers": {
"Authorization": "Bearer ${REGISTRY_TOKEN}",
"X-API-Key": "${API_KEY}"
},
"params": {
"version": "latest"
}
}
}
}
```
Environment variables in the format `${VAR_NAME}` are automatically expanded from your environment.
### Using Namespaced Registries
Once configured, install resources using the namespace syntax:
```bash
# Install from a configured registry
npx shadcn@latest add @v0/dashboard
# Install from private registry
npx shadcn@latest add @private/button
# Install multiple resources
npx shadcn@latest add @acme/header @internal/auth-utils
```
### Example: Multiple Registry Setup
```json title="components.json"
{
"registries": {
"@shadcn": "https://ui.shadcn.com/r/{name}.json",
"@company-ui": {
"url": "https://registry.company.com/ui/{name}.json",
"headers": {
"Authorization": "Bearer ${COMPANY_TOKEN}"
}
},
"@team": {
"url": "https://team.company.com/{name}.json",
"params": {
"team": "frontend",
"version": "${REGISTRY_VERSION}"
}
}
}
}
```
This configuration allows you to:
- Install public components from shadcn/ui
- Access private company UI components with authentication
- Use team-specific resources with versioning
For more information about authentication, see the <Link href="/docs/registry/authentication">Authentication</Link> documentation.

View File

@@ -0,0 +1,267 @@
---
title: MCP Server
description: Use the shadcn MCP server to browse, search, and install components from registries.
---
The shadcn MCP Server allows AI assistants to interact with items from registries. You can browse available components, search for specific ones, and install them directly into your project using natural language.
For example, you can ask an AI assistant to "Build a landing page using components from the acme registry" or "Find me a login form from the shadcn registry".
Registries are configured in your project's `components.json` file.
```json title="components.json" showLineNumbers
{
"registries": {
"@acme": "https://acme.com/r/{name}.json"
}
}
```
---
## Quick Start
Select your MCP client and follow the instructions to configure the shadcn MCP server. If you'd like to do it manually, see the [Configuration](#configuration) section.
<Tabs defaultValue="claude">
<TabsList>
<TabsTrigger value="claude">Claude Code</TabsTrigger>
<TabsTrigger value="cursor">Cursor</TabsTrigger>
<TabsTrigger value="vscode">VS Code</TabsTrigger>
</TabsList>
<TabsContent value="claude" className="mt-4">
**Run the following command** in your project:
```bash
npx shadcn@latest mcp init --client claude
```
**Restart Claude Code** and try the following prompts:
- Show me all available components in the shadcn registry
- Add the button, dialog and card components to my project
- Create a contact form using components from the shadcn registry
**Note:** You can use `/mcp` command in Claude Code to debug the MCP server.
</TabsContent>
<TabsContent value="cursor" className="mt-4">
**Run the following command** in your project:
```bash
npx shadcn@latest mcp init --client cursor
```
Open **Cursor Settings** and **Enable the MCP server** for shadcn. Then try the following prompts:
- Show me all available components in the shadcn registry
- Add the button, dialog and card components to my project
- Create a contact form using components from the shadcn registry
</TabsContent>
<TabsContent value="vscode" className="mt-4">
**Run the following command** in your project:
```bash
npx shadcn@latest mcp init --client vscode
```
Open `.vscode/mcp.json` and click **Start** next to the shadcn server. Then try the following prompts with GitHub Copilot:
- Show me all available components in the shadcn registry
- Add the button, dialog and card components to my project
- Create a contact form using components from the shadcn registry
</TabsContent>
</Tabs>
---
## What is MCP?
[Model Context Protocol (MCP)](https://modelcontextprotocol.io) is an open protocol that enables AI assistants to securely connect to external data sources and tools. With the shadcn MCP server, your AI assistant gains direct access to:
- **Browse Components** - List all available components, blocks, and templates from any configured registry
- **Search Across Registries** - Find specific components by name or functionality across multiple sources
- **Install with Natural Language** - Add components using simple conversational prompts like "add a login form"
- **Support for Multiple Registries** - Access public registries, private company libraries, and third-party sources
## How It Works
The MCP server acts as a bridge between your AI assistant, component registries and the shadcn CLI.
1. **Registry Connection** - MCP connects to configured registries (shadcn/ui, private registries, third-party sources)
2. **Natural Language** - You describe what you need in plain English
3. **AI Processing** - The assistant translates your request into registry commands
4. **Component Delivery** - Resources are fetched and installed in your project
### Supported Registries
The shadcn MCP server works out of the box with any shadcn-compatible registry.
- **shadcn/ui Registry** - The default registry with all shadcn/ui components
- **Private Registries** - Your company's internal component libraries
- **Third-Party Registries** - Any registry following the shadcn registry specification
- **Namespaced Registries** - Multiple registries configured with `@namespace` syntax
---
## Configuration
The shadcn MCP server works with any MCP client. Here are the instructions for the most popular ones.
### Claude Code
To use the shadcn MCP server with Claude Code, add the following configuration to your project's `.mcp.json` file:
```json title=".mcp.json" showLineNumbers
{
"mcpServers": {
"shadcn": {
"command": "npx",
"args": ["shadcn@latest", "mcp"]
}
}
}
```
After adding the configuration, restart Claude Code and run `/mcp` to see the shadcn MCP server in the list. If you see `Connected`, you're good to go.
See the [Claude Code MCP documentation](https://docs.anthropic.com/en/docs/claude-code/mcp) for more details.
### Cursor
To configure MCP in Cursor, add the shadcn server to your project's `.cursor/mcp.json` configuration file:
```json title=".cursor/mcp.json" showLineNumbers
{
"mcpServers": {
"shadcn": {
"command": "npx",
"args": ["shadcn@latest", "mcp"]
}
}
}
```
After adding the configuration, enable the shadcn MCP server in Cursor Settings.
Once enabled, you should see a green dot next to the shadcn server in the MCP server list and a list of available tools.
See the [Cursor MCP documentation](https://docs.cursor.com/en/context/mcp#using-mcp-json) for more details.
### VS Code
To configure MCP in VS Code with GitHub Copilot, add the shadcn server to your project's `.vscode/mcp.json` configuration file:
```json title=".vscode/mcp.json" showLineNumbers
{
"mcpServers": {
"shadcn": {
"command": "npx",
"args": ["shadcn@latest", "mcp"]
}
}
}
```
After adding the configuration, open `.vscode/mcp.json` and click **Start** next to the shadcn server.
See the [VS Code MCP documentation](https://code.visualstudio.com/docs/copilot/chat/mcp-servers) for more details.
---
## Configuring Registries
The MCP server supports multiple registries through your project's `components.json` configuration. This allows you to access components from various sources including private registries and third-party providers.
<Callout>
**Note:** No configuration is needed to access standard shadcn/ui registry.
</Callout>
Configure additional registries in your `components.json`:
```json title="components.json" showLineNumbers
{
"registries": {
"@acme": "https://registry.acme.com/{name}.json",
"@internal": {
"url": "https://internal.company.com/{name}.json",
"headers": {
"Authorization": "Bearer ${REGISTRY_TOKEN}"
}
}
}
}
```
---
### Authentication
For private registries requiring authentication, set environment variables in your `.env.local`:
```bash title=".env.local"
REGISTRY_TOKEN=your_token_here
API_KEY=your_api_key_here
```
For more details on registry configuration, see the [Namespaces documentation](/docs/registry/namespace).
---
## Example Prompts
Once MCP is configured, you can use natural language to interact with registries:
### Browse & Search
- "Show me all available components in the shadcn registry"
- "Find me a login form from the shadcn registry"
### Install Components
- "Add the button component to my project"
- "Create a login form using shadcn components"
### Work with Namespaces
- "Show me components from @acme registry"
- "Install @internal/auth-form"
- "Build me a landing page using hero, features and testimonials components from the @acme registry"
---
## Troubleshooting
### MCP Not Responding
If the MCP server isn't responding to prompts:
1. **Check Configuration** - Verify the MCP server is properly configured and enabled in your MCP client
2. **Restart MCP Client** - Restart your MCP client after configuration changes
3. **Verify Installation** - Ensure `shadcn` is installed in your project
4. **Check Network** - Confirm you can access the configured registries
### Registry Access Issues
If components aren't loading from registries:
1. **Check components.json** - Verify registry URLs are correct
2. **Test Authentication** - Ensure environment variables are set for private registries
3. **Verify Registry** - Confirm the registry is online and accessible
4. **Check Namespace** - Ensure namespace syntax is correct (`@namespace/component`)
### Installation Failures
If components fail to install:
1. **Check Project Setup** - Ensure you have a valid `components.json` file
2. **Verify Paths** - Confirm the target directories exist
3. **Check Permissions** - Ensure write permissions for component directories
4. **Review Dependencies** - Check that required dependencies are installed
---
## Learn More
- [Registry Documentation](/docs/registry) - Complete guide to shadcn registries
- [Namespaces](/docs/registry/namespace) - Configure multiple registry sources
- [Authentication](/docs/registry/authentication) - Secure your private registries
- [MCP Specification](https://modelcontextprotocol.io) - Learn about Model Context Protocol

View File

@@ -0,0 +1,397 @@
---
title: Authentication
description: Secure your registry with authentication for private and personalized components.
---
Authentication lets you run private registries, control who can access your components, and give different teams or users different content. This guide shows common authentication patterns and how to set them up.
Authentication enables these use cases:
- **Private Components**: Keep your business logic and internal components secure
- **Team-Specific Resources**: Give different teams different components
- **Access Control**: Limit who can see sensitive or experimental components
- **Usage Analytics**: See who's using which components in your organization
- **Licensing**: Control who gets premium or licensed components
## Common Authentication Patterns
### Token-Based Authentication
The most common approach uses Bearer tokens or API keys:
```json title="components.json"
{
"registries": {
"@private": {
"url": "https://registry.company.com/{name}.json",
"headers": {
"Authorization": "Bearer ${REGISTRY_TOKEN}"
}
}
}
}
```
Set your token in environment variables:
```bash title=".env.local"
REGISTRY_TOKEN=your_secret_token_here
```
### API Key Authentication
Some registries use API keys in headers:
```json title="components.json"
{
"registries": {
"@company": {
"url": "https://api.company.com/registry/{name}.json",
"headers": {
"X-API-Key": "${API_KEY}",
"X-Workspace-Id": "${WORKSPACE_ID}"
}
}
}
}
```
### Query Parameter Authentication
For simpler setups, use query parameters:
```json title="components.json"
{
"registries": {
"@internal": {
"url": "https://registry.company.com/{name}.json",
"params": {
"token": "${ACCESS_TOKEN}"
}
}
}
}
```
This creates: `https://registry.company.com/button.json?token=your_token`
## Server-Side Implementation
Here's how to add authentication to your registry server:
### Next.js API Route Example
```typescript title="app/api/registry/[name]/route.ts"
import { NextRequest, NextResponse } from "next/server"
export async function GET(
request: NextRequest,
{ params }: { params: { name: string } }
) {
// Get token from Authorization header.
const authHeader = request.headers.get("authorization")
const token = authHeader?.replace("Bearer ", "")
// Or from query parameters.
const queryToken = request.nextUrl.searchParams.get("token")
// Check if token is valid.
if (!isValidToken(token || queryToken)) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
}
// Check if token can access this component.
if (!hasAccessToComponent(token, params.name)) {
return NextResponse.json({ error: "Forbidden" }, { status: 403 })
}
// Return the component.
const component = await getComponent(params.name)
return NextResponse.json(component)
}
function isValidToken(token: string | null) {
// Add your token validation logic here.
// Check against database, JWT validation, etc.
return token === process.env.VALID_TOKEN
}
function hasAccessToComponent(token: string, componentName: string) {
// Add role-based access control here.
// Check if token can access specific component.
return true // Your logic here.
}
```
### Express.js Example
```javascript title="server.js"
app.get("/registry/:name.json", (req, res) => {
const token = req.headers.authorization?.replace("Bearer ", "")
if (!isValidToken(token)) {
return res.status(401).json({ error: "Unauthorized" })
}
const component = getComponent(req.params.name)
if (!component) {
return res.status(404).json({ error: "Component not found" })
}
res.json(component)
})
```
## Advanced Authentication Patterns
### Team-Based Access
Give different teams different components:
```typescript title="api/registry/route.ts"
async function GET(request: NextRequest) {
const token = extractToken(request)
const team = await getTeamFromToken(token)
// Get components for this team.
const components = await getComponentsForTeam(team)
return NextResponse.json(components)
}
```
### User-Personalized Registries
Give users components based on their preferences:
```typescript
async function GET(request: NextRequest) {
const user = await authenticateUser(request)
// Get user's style and framework preferences.
const preferences = await getUserPreferences(user.id)
// Get personalized component version.
const component = await getPersonalizedComponent(params.name, preferences)
return NextResponse.json(component)
}
```
### Temporary Access Tokens
Use expiring tokens for better security:
```typescript
interface TemporaryToken {
token: string
expiresAt: Date
scope: string[]
}
async function validateTemporaryToken(token: string) {
const tokenData = await getTokenData(token)
if (!tokenData) return false
if (new Date() > tokenData.expiresAt) return false
return true
}
```
## Multi-Registry Authentication
With [namespaced registries](/docs/registry/namespace), you can set up multiple registries with different authentication:
```json title="components.json"
{
"registries": {
"@public": "https://public.company.com/{name}.json",
"@internal": {
"url": "https://internal.company.com/{name}.json",
"headers": {
"Authorization": "Bearer ${INTERNAL_TOKEN}"
}
},
"@premium": {
"url": "https://premium.company.com/{name}.json",
"headers": {
"X-License-Key": "${LICENSE_KEY}"
}
}
}
}
```
This lets you:
- Mix public and private registries
- Use different authentication per registry
- Organize components by access level
## Security Best Practices
### Use Environment Variables
Never commit tokens to version control. Always use environment variables:
```bash title=".env.local"
REGISTRY_TOKEN=your_secret_token_here
API_KEY=your_api_key_here
```
Then reference them in `components.json`:
```json
{
"registries": {
"@private": {
"url": "https://registry.company.com/{name}.json",
"headers": {
"Authorization": "Bearer ${REGISTRY_TOKEN}"
}
}
}
}
```
### Use HTTPS
Always use HTTPS URLs for registries to protect your tokens in transit:
```json
{
"@secure": "https://registry.company.com/{name}.json" // ✅
"@insecure": "http://registry.company.com/{name}.json" // ❌
}
```
### Add Rate Limiting
Protect your registry from abuse:
```typescript
import rateLimit from "express-rate-limit"
const limiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100, // limit each IP to 100 requests per windowMs
})
app.use("/registry", limiter)
```
### Rotate Tokens
Change access tokens regularly:
```typescript
// Create new token with expiration.
function generateToken() {
const token = crypto.randomBytes(32).toString("hex")
const expiresAt = new Date(Date.now() + 30 * 24 * 60 * 60 * 1000) // 30 days.
return { token, expiresAt }
}
```
### Log Access
Track registry access for security and analytics:
```typescript
async function logAccess(request: Request, component: string, userId: string) {
await db.accessLog.create({
timestamp: new Date(),
userId,
component,
ip: request.ip,
userAgent: request.headers["user-agent"],
})
}
```
## Testing Authentication
Test your authenticated registry locally:
```bash
# Test with curl.
curl -H "Authorization: Bearer your_token" \
https://registry.company.com/button.json
# Test with the CLI.
REGISTRY_TOKEN=your_token npx shadcn@latest add @private/button
```
## Error Handling
The shadcn CLI handles authentication errors gracefully:
- **401 Unauthorized**: Token is invalid or missing
- **403 Forbidden**: Token lacks permission for this resource
- **429 Too Many Requests**: Rate limit exceeded
### Custom Error Messages
Your registry server can return custom error messages in the response body, and the CLI will display them to users:
```typescript
// Registry server returns custom error
return NextResponse.json(
{
error: "Unauthorized",
message: "Your subscription has expired. Please renew at company.com/billing"
},
{ status: 403 }
)
```
The user will see:
```txt
Your subscription has expired. Please renew at company.com/billing
```
This helps provide context-specific guidance:
```typescript
// Different error messages for different scenarios
if (!token) {
return NextResponse.json(
{
error: "Unauthorized",
message: "Authentication required. Set REGISTRY_TOKEN in your .env.local file"
},
{ status: 401 }
)
}
if (isExpiredToken(token)) {
return NextResponse.json(
{
error: "Unauthorized",
message: "Token expired. Request a new token at company.com/tokens"
},
{ status: 401 }
)
}
if (!hasTeamAccess(token, component)) {
return NextResponse.json(
{
error: "Forbidden",
message: `Component '${component}' is restricted to the Design team`
},
{ status: 403 }
)
}
```
## Next Steps
To set up authentication with multiple registries and advanced patterns, see the [Namespaced Registries](/docs/registry/namespace) documentation. It covers:
- Setting up multiple authenticated registries
- Using different authentication per namespace
- Cross-registry dependency resolution
- Advanced authentication patterns

View File

@@ -3,23 +3,27 @@ title: Getting Started
description: Learn how to get setup and run your own component registry.
---
This guide will walk you through the process of setting up your own component registry.
It assumes you already have a project with components and would like to turn it into a registry.
This guide will walk you through the process of setting up your own component registry. It assumes you already have a project with components and would like to turn it into a registry.
If you're starting a new registry project, you can use the [registry template](https://github.com/shadcn-ui/registry-template) as a starting point. We have already configured it for you.
## Requirements
You are free to design and host your custom registry as you see fit. The only requirement is that your registry items must be valid JSON files that conform to the [registry-item schema specification](/docs/registry/registry-item-json).
If you'd like to see an example of a registry, we have a [template project](https://github.com/shadcn-ui/registry-template) for you to use as a starting point.
## registry.json
The `registry.json` file is only required if you're using the `shadcn` CLI to build your registry.
The `registry.json` is the entry point for the registry. It contains the registry's name, homepage, and defines all the items present in the registry.
If you're using a different build system, you can skip this step as long as your build system produces valid JSON files that conform to the [registry-item schema specification](/docs/registry/registry-item-json).
Your registry must have this file (or JSON payload) present at the root of the registry endpoint. The registry endpoint is the URL where your registry is hosted.
<Steps>
The `shadcn` CLI will automatically generate this file for you when you run the `build` command.
### Add a registry.json file
## Add a registry.json file
Create a `registry.json` file in the root of your project. Your project can be a Next.js, Remix, Vite, or any other project that supports React.
Create a `registry.json` file in the root of your project. Your project can be a Next.js, Vite, Vue, Svelte, PHP or any other framework as long as it supports serving JSON over HTTP.
```json title="registry.json" showLineNumbers
{
@@ -34,12 +38,8 @@ Create a `registry.json` file in the root of your project. Your project can be a
This `registry.json` file must conform to the [registry schema specification](/docs/registry/registry-json).
</Steps>
## Add a registry item
<Steps>
### Create your component
Add your first component. Here's an example of a simple `<HelloWorld />` component:
@@ -98,16 +98,10 @@ For every file you add, you must specify the `path` and `type` of the file. The
You can read more about the registry item schema and file types in the [registry item schema docs](/docs/registry/registry-item-json).
</Steps>
## Build your registry
<Steps>
### Install the shadcn CLI
Note: the `build` command is currently only available in the `shadcn@canary` version of the CLI.
```bash
npm install shadcn@canary
```
@@ -140,8 +134,6 @@ You can change the output directory by passing the `--output` option. See the [s
</Callout>
</Steps>
## Serve your registry
If you're running your registry on Next.js, you can now serve your registry by running the `next` server. The command might differ for other frameworks.
@@ -156,24 +148,13 @@ Your files will now be served at `http://localhost:3000/r/[NAME].json` eg. `http
To make your registry available to other developers, you can publish it by deploying your project to a public URL.
## Adding Auth
The `shadcn` CLI does not offer a built-in way to add auth to your registry. We recommend handling authorization on your registry server.
A common simple approach is to use a `token` query parameter to authenticate requests to your registry. e.g. `http://localhost:3000/r/hello-world.json?token=[SECURE_TOKEN_HERE]`.
Use the secure token to authenticate requests and return a 401 Unauthorized response if the token is invalid. Both the `shadcn` CLI and `Open in v0` will handle the 401 response and display a message to the user.
<Callout className="mt-6">
**Note:** Make sure to encrypt and expire tokens.
</Callout>
## Guidelines
Here are some guidelines to follow when building components for a registry.
- Place your registry item in the `registry/[STYLE]/[NAME]` directory. I'm using `new-york` as an example. It can be anything you want as long as it's nested under the `registry` directory.
- The following properties are required for the block definition: `name`, `description`, `type` and `files`.
- It is recommended to add a proper name and description to your registry item. This helps LLMs understand the component and its purpose.
- Make sure to list all registry dependencies in `registryDependencies`. A registry dependency is the name of the component in the registry eg. `input`, `button`, `card`, etc or a URL to a registry item eg. `http://localhost:3000/r/editor.json`.
- Make sure to list all dependencies in `dependencies`. A dependency is the name of the package in the registry eg. `zod`, `sonner`, etc. To set a version, you can use the `name@version` format eg. `zod@^3.20.0`.
- **Imports should always use the `@/registry` path.** eg. `import { HelloWorld } from "@/registry/new-york/hello-world/hello-world"`
@@ -186,3 +167,7 @@ To install a registry item using the `shadcn` CLI, use the `add` command followe
```bash
npx shadcn@latest add http://localhost:3000/r/hello-world.json
```
See the [Namespaced
Registries](/docs/registry/namespaced-registries) docs for more information on
how to install registry items from a namespaced registry.

View File

@@ -1,5 +1,5 @@
---
title: Registry
title: Introduction
description: Run your own code registry.
---
@@ -30,8 +30,50 @@ You can use the `shadcn` CLI to run your own code registry. Running your own reg
</figcaption>
</figure>
## Requirements
Ready to create your own registry? In the next section, we'll walk you through setting up your own custom registry step-by-step, from creating your first component to publishing it for others to use.
You are free to design and host your custom registry as you see fit. The only requirement is that your registry items must be valid JSON files that conform to the [registry-item schema specification](/docs/registry/registry-item-json).
<div className="mt-6 grid gap-4 sm:grid-cols-2">
<LinkedCard href="/docs/registry/getting-started" className="items-start text-sm md:p-6">
<div className="font-medium">Getting Started</div>
<div className="text-muted-foreground">
Set up and build your own registry
</div>
</LinkedCard>
If you'd like to see an example of a registry, we have a [template project](https://github.com/shadcn-ui/registry-template) for you to use as a starting point.
<LinkedCard
href="/docs/registry/authentication"
className="items-start text-sm md:p-6"
>
<div className="font-medium">Authentication</div>
<div className="text-muted-foreground">
Secure your registry with authentication
</div>
</LinkedCard>
<LinkedCard
href="/docs/registry/namespace"
className="items-start text-sm md:p-6"
>
<div className="font-medium">Namespaces</div>
<div className="text-muted-foreground">
Configure registries with namespaces
</div>
</LinkedCard>
<LinkedCard
href="/docs/registry/examples"
className="items-start text-sm md:p-6"
>
<div className="font-medium">Examples</div>
<div className="text-muted-foreground">
Registry item examples and configurations
</div>
</LinkedCard>
<LinkedCard
href="/docs/registry/registry-json"
className="items-start text-sm md:p-6"
>
<div className="font-medium">Schema</div>
<div className="text-muted-foreground">
Schema specification for registry.json
</div>
</LinkedCard>
</div>

View File

@@ -0,0 +1,102 @@
---
title: MCP Server
description: MCP support for registry developers
---
The [shadcn MCP server](/docs/mcp) works out of the box with any shadcn-compatible registry. You do not need to do anything special to enable MCP support for your registry.
See the [MCP documentation](/docs/mcp) for more information on how to use the shadcn MCP server.
---
## Configuring MCP
Ask your registry consumers to configure your registry in their `components.json` file and install the shadcn MCP server:
<Tabs defaultValue="claude">
<TabsList>
<TabsTrigger value="claude">Claude Code</TabsTrigger>
<TabsTrigger value="cursor">Cursor</TabsTrigger>
<TabsTrigger value="vscode">VS Code</TabsTrigger>
</TabsList>
<TabsContent value="claude" className="mt-4">
**Configure your registry** in your `components.json` file:
```json title="components.json" showLineNumbers
{
"registries": {
"@acme": "https://acme.com/r/{name}.json"
}
}
```
**Run the following command** in your project:
```bash
npx shadcn@latest mcp init --client claude
```
**Restart Claude Code** and try the following prompts:
- Show me all available components in the shadcn registry
- Add the button, dialog and card components to my project
- Create a contact form using components from the shadcn registry
**Note:** You can use `/mcp` command in Claude Code to debug the MCP server.
</TabsContent>
<TabsContent value="cursor" className="mt-4">
**Configure your registry** in your `components.json` file:
```json title="components.json" showLineNumbers
{
"registries": {
"@acme": "https://acme.com/r/{name}.json"
}
}
```
**Run the following command** in your project:
```bash
npx shadcn@latest mcp init --client cursor
```
Open **Cursor Settings** and **Enable the MCP server** for shadcn. Then try the following prompts:
- Show me all available components in the shadcn registry
- Add the button, dialog and card components to my project
- Create a contact form using components from the shadcn registry
</TabsContent>
<TabsContent value="vscode" className="mt-4">
**Configure your registry** in your `components.json` file:
```json title="components.json" showLineNumbers
{
"registries": {
"@acme": "https://acme.com/r/{name}.json"
}
}
```
**Run the following command** in your project:
```bash
npx shadcn@latest mcp init --client vscode
```
Open `.vscode/mcp.json` and click **Start** next to the shadcn server. Then try the following prompts with GitHub Copilot:
- Show me all available components in the shadcn registry
- Add the button, dialog and card components to my project
- Create a contact form using components from the shadcn registry
</TabsContent>
</Tabs>
---
### Best Practices
Here are some best practices for MCP-compatible registries:
1. **Clear Descriptions**: Add concise, informative descriptions that help AI assistants understand what a registry item is for and how to use it.
2. **Proper Dependencies**: List all `dependencies` accurately so MCP can install them automatically.
3. **Registry Dependencies**: Use `registryDependencies` to indicate relationships between items.
4. **Consistent Naming**: Use kebab-case for component names and maintain consistency across your registry.

View File

@@ -1,10 +1,13 @@
{
"title": "Registry",
"pages": [
"index",
"getting-started",
"faq",
"open-in-v0",
"namespace",
"authentication",
"examples",
"mcp",
"open-in-v0",
"registry-json",
"registry-item-json"
]

View File

@@ -0,0 +1,957 @@
---
title: Namespaces
description: Configure and use multiple resource registries with namespace support.
---
Namespaced registries let you configure multiple resource sources in one project. This means you can install components, libraries, utilities, AI prompts, configuration files, and other resources from various registries, whether they're public, third-party, or your own custom private libraries.
## Table of Contents
- [Overview](#overview)
- [Decentralized Namespace System](#decentralized-namespace-system)
- [Getting Started](#getting-started)
- [Registry Naming Convention](#registry-naming-convention)
- [Configuration](#configuration)
- [Authentication & Security](#authentication--security)
- [Versioning](#versioning)
- [Dependency Resolution](#dependency-resolution)
- [Built-in Registries](#built-in-registries)
- [CLI Commands](#cli-commands)
- [Error Handling](#error-handling)
- [Creating Your Own Registry](#creating-your-own-registry)
- [Example Configurations](#example-configurations)
- [Technical Details](#technical-details)
- [Best Practices](#best-practices)
- [Troubleshooting](#troubleshooting)
## Overview
Registry namespaces are prefixed with `@` and provide a way to organize and reference resources from different sources. Resources can be any type of content: components, libraries, utilities, hooks, AI prompts, configuration files, themes, and more. For example:
- `@shadcn/button` - UI component from the shadcn registry
- `@v0/dashboard` - Dashboard component from the v0 registry
- `@ai-elements/input` - AI prompt input from an AI elements registry
- `@acme/auth-utils` - Authentication utilities from your company's private registry
- `@ai/chatbot-rules` - AI prompt rules from an AI resources registry
- `@themes/dark-mode` - Theme configuration from a themes registry
## Decentralized Namespace System
We intentionally designed the namespace system to be decentralized. There is no central registrar for namespaces. You are free to create and use any namespace you want.
This decentralized approach gives you complete flexibility to organize your resources however makes sense for your organization.
You can create multiple registries for different purposes:
```json title="components.json" showLineNumbers
{
"registries": {
"@acme-ui": "https://registry.acme.com/ui/{name}.json",
"@acme-docs": "https://registry.acme.com/docs/{name}.json",
"@acme-ai": "https://registry.acme.com/ai/{name}.json",
"@acme-themes": "https://registry.acme.com/themes/{name}.json",
"@acme-internal": {
"url": "https://internal.acme.com/registry/{name}.json",
"headers": {
"Authorization": "Bearer ${INTERNAL_TOKEN}"
}
}
}
}
```
This allows you to:
- **Organize by type**: Separate UI components, documentation, AI resources, etc.
- **Organize by team**: Different teams can maintain their own registries
- **Organize by visibility**: Public vs. private resources
- **Organize by version**: Stable vs. experimental registries
- **No naming conflicts**: Since there's no central authority, you don't need to worry about namespace collisions
### Examples of Multi-Registry Setups
#### By Resource Type
```json title="components.json" showLineNumbers
{
"@components": "https://cdn.company.com/components/{name}.json",
"@hooks": "https://cdn.company.com/hooks/{name}.json",
"@utils": "https://cdn.company.com/utils/{name}.json",
"@prompts": "https://cdn.company.com/ai-prompts/{name}.json"
}
```
#### By Team or Department
```json title="components.json" showLineNumbers
{
"@design": "https://design.company.com/registry/{name}.json",
"@engineering": "https://eng.company.com/registry/{name}.json",
"@marketing": "https://marketing.company.com/registry/{name}.json"
}
```
#### By Stability
```json title="components.json" showLineNumbers
{
"@stable": "https://registry.company.com/stable/{name}.json",
"@latest": "https://registry.company.com/beta/{name}.json",
"@experimental": "https://registry.company.com/experimental/{name}.json"
}
```
## Getting Started
### Installing Resources
Once configured, you can install resources using the namespace syntax:
```bash
npx shadcn@beta add @v0/dashboard
```
or multiple resources at once:
```bash
npx shadcn@beta add @acme/header @lib/auth-utils @ai/chatbot-rules
```
### Quick Configuration
Add registries to your `components.json`:
```json title="components.json"
{
"registries": {
"@v0": "https://v0.dev/chat/b/{name}",
"@acme": "https://registry.acme.com/resources/{name}.json"
}
}
```
Then start installing:
```bash
npx shadcn@beta add @acme/button
```
## Registry Naming Convention
Registry names must follow these rules:
- Start with `@` symbol
- Contain only alphanumeric characters, hyphens, and underscores
- Examples of valid names: `@v0`, `@acme-ui`, `@my_company`
The pattern for referencing resources is: `@namespace/resource-name`
## Configuration
Namespaced registries are configured in your `components.json` file under the `registries` field.
### Basic Configuration
The simplest way to configure a registry is with a URL template string:
```json title="components.json"
{
"registries": {
"@v0": "https://v0.dev/chat/b/{name}",
"@acme": "https://registry.acme.com/resources/{name}.json",
"@lib": "https://lib.company.com/utilities/{name}",
"@ai": "https://ai-resources.com/r/{name}.json"
}
}
```
> **Note:** The `{name}` placeholder in the URL is automatically parsed and replaced with the resource name when you run `npx shadcn@beta add @namespace/resource-name`. For example, `@acme/button` becomes `https://registry.acme.com/resources/button.json`. See [URL Pattern System](#url-pattern-system) for more details.
### Advanced Configuration
For registries that require authentication or additional parameters, use the object format:
```json title="components.json"
{
"registries": {
"@private": {
"url": "https://api.company.com/registry/{name}.json",
"headers": {
"Authorization": "Bearer ${REGISTRY_TOKEN}",
"X-API-Key": "${API_KEY}"
},
"params": {
"version": "latest",
"format": "json"
}
}
}
}
```
> **Note:** Environment variables in the format `${VAR_NAME}` are automatically expanded from your environment (process.env). This works in URLs, headers, and params. For example, `${REGISTRY_TOKEN}` will be replaced with the value of `process.env.REGISTRY_TOKEN`. See [Authentication & Security](#authentication--security) for more details on using environment variables.
### URL Pattern System
Registry URLs support the following placeholders:
### `{name}` Placeholder (required)
The `{name}` placeholder is replaced with the resource name:
```json title="components.json" showLineNumbers
{
"@acme": "https://registry.acme.com/{name}.json"
}
```
When installing `@acme/button`, the URL becomes: `https://registry.acme.com/button.json`
When installing `@acme/auth-utils`, the URL becomes: `https://registry.acme.com/auth-utils.json`
### `{style}` Placeholder (optional)
The `{style}` placeholder is replaced with the current style configuration:
```json
{
"@themes": "https://registry.example.com/{style}/{name}.json"
}
```
With style set to `new-york`, installing `@themes/card` resolves to: `https://registry.example.com/new-york/card.json`
The style placeholder is optional. Use this when you want to serve different versions of the same resource. For example, you can serve a different version of a component for each style.
## Authentication & Security
### Environment Variables
Use environment variables to securely store credentials:
```json title="components.json"
{
"registries": {
"@private": {
"url": "https://api.company.com/registry/{name}.json",
"headers": {
"Authorization": "Bearer ${REGISTRY_TOKEN}"
}
}
}
}
```
Then set the environment variable:
```bash title=".env.local"
REGISTRY_TOKEN=your_secret_token_here
```
### Authentication Methods
#### Bearer Token (OAuth 2.0)
```json
{
"@github": {
"url": "https://api.github.com/repos/org/registry/contents/{name}.json",
"headers": {
"Authorization": "Bearer ${GITHUB_TOKEN}"
}
}
}
```
#### API Key in Headers
```json title="components.json" showLineNumbers
{
"@private": {
"url": "https://api.company.com/registry/{name}",
"headers": {
"X-API-Key": "${API_KEY}"
}
}
}
```
#### Basic Authentication
```json title="components.json" showLineNumbers
{
"@internal": {
"url": "https://registry.company.com/{name}.json",
"headers": {
"Authorization": "Basic ${BASE64_CREDENTIALS}"
}
}
}
```
#### Query Parameter Authentication
```json title="components.json" showLineNumbers
{
"@secure": {
"url": "https://registry.example.com/{name}.json",
"params": {
"api_key": "${API_KEY}",
"client_id": "${CLIENT_ID}",
"signature": "${REQUEST_SIGNATURE}"
}
}
}
```
#### Multiple Authentication Methods
Some registries require multiple authentication methods:
```json title="components.json" showLineNumbers
{
"@enterprise": {
"url": "https://api.enterprise.com/v2/registry/{name}",
"headers": {
"Authorization": "Bearer ${ACCESS_TOKEN}",
"X-API-Key": "${API_KEY}",
"X-Workspace-Id": "${WORKSPACE_ID}"
},
"params": {
"version": "latest"
}
}
}
```
### Security Considerations
When working with namespaced registries, especially third-party or public ones, security is paramount. Here's how we handle security:
### Resource Validation
All resources fetched from registries are validated against our registry item schema before installation. This ensures:
- **Structure validation**: Resources must conform to the expected JSON schema
- **Type safety**: Resource types are validated (`registry:ui`, `registry:lib`, etc.)
- **No arbitrary code execution**: Resources are data files, not executable scripts
### Environment Variable Security
Environment variables used for authentication are:
- **Never logged**: The CLI never logs or displays environment variable values
- **Expanded at runtime**: Variables are only expanded when needed, not stored
- **Isolated per registry**: Each registry maintains its own authentication context
Example of secure configuration:
```json title="components.json" showLineNumbers
{
"registries": {
"@private": {
"url": "https://api.company.com/registry/{name}.json",
"headers": {
"Authorization": "Bearer ${PRIVATE_REGISTRY_TOKEN}"
}
}
}
}
```
Never commit actual tokens to version control. Use `.env.local`:
```bash title=".env.local"
PRIVATE_REGISTRY_TOKEN=actual_token_here
```
### HTTPS Enforcement
We strongly recommend using HTTPS for all registry URLs:
- **Encrypted transport**: Prevents man-in-the-middle attacks
- **Certificate validation**: Ensures you're connecting to the legitimate registry
- **Credential protection**: Headers and tokens are encrypted in transit
```json title="components.json" showLineNumbers
{
"registries": {
"@secure": "https://registry.example.com/{name}.json", // ✅ Good
"@insecure": "http://registry.example.com/{name}.json" // ❌ Avoid
}
}
```
### Content Security
Resources from registries are treated as data, not code:
1. **JSON parsing only**: Resources must be valid JSON
2. **Schema validation**: Must match the registry item schema
3. **File path restrictions**: Files can only be written to configured paths
4. **No script execution**: The CLI doesn't execute any code from registry resources
### Registry Trust Model
The namespace system operates on a trust model:
- **You trust what you install**: Only add registries you trust to your configuration
- **Explicit configuration**: Registries must be explicitly configured in `components.json`
- **No automatic registry discovery**: The CLI never automatically adds registries
- **Dependency transparency**: All dependencies are clearly listed in registry items
### Best Practices for Registry Operators
If you're running your own registry:
1. **Use HTTPS always**: Never serve registry content over HTTP
2. **Implement authentication**: Require API keys or tokens for private registries
3. **Rate limiting**: Protect your registry from abuse
4. **Content validation**: Validate resources before serving them
Example secure registry setup:
```json title="components.json" showLineNumbers
{
"@company": {
"url": "https://registry.company.com/v1/{name}.json",
"headers": {
"Authorization": "Bearer ${COMPANY_TOKEN}",
"X-Registry-Version": "1.0"
}
}
}
```
### Inspecting Resources Before Installation
The CLI provides transparency about what's being installed. You can see the payload of a registry item using the following command:
```bash
npx shadcn@beta view @acme/button
```
This will output the payload of the registry item to the console.
## Dependency Resolution
### Basic Dependency Resolution
Resources can have dependencies across different registries:
```json title="registry-item.json" showLineNumbers
{
"name": "dashboard",
"type": "registry:block",
"registryDependencies": [
"@shadcn/card", // From default registry
"@v0/chart", // From v0 registry
"@acme/data-table", // From acme registry
"@lib/data-fetcher", // Utility library
"@ai/analytics-prompt" // AI prompt resource
]
}
```
The CLI automatically resolves and installs all dependencies from their respective registries.
### Advanced Dependency Resolution
Understanding how dependencies are resolved internally is important if you're developing registries or need to customize third-party resources.
### How Resolution Works
When you run `npx shadcn@beta add @namespace/resource`, the CLI does the following:
1. **Clears registry context** to start fresh
2. **Fetches the main resource** from the specified registry
3. **Recursively resolves dependencies** from their respective registries
4. **Applies topological sorting** to ensure proper installation order
5. **Deduplicates files** based on target paths (last one wins)
6. **Deep merges configurations** (tailwind, cssVars, css, envVars)
This means that if you run the following command:
```bash
npx shadcn@beta add @acme/auth @custom/login-form
```
The `login-form.ts` from `@custom/login-form` will override the `login-form.ts` from `@acme/auth` because it's resolved last.
### Overriding Third-Party Resources
You can leverage the dependency resolution process to override any third-party resource by adding them to your custom resource under `registryDependencies` and overriding with your own custom values.
#### Example: Customizing a Third-Party Button
Let's say you want to customize a button from a vendor registry:
**1. Original vendor button** (`@vendor/button`):
```json title="button.json" showLineNumbers
{
"name": "button",
"type": "registry:ui",
"files": [
{
"path": "components/ui/button.tsx",
"type": "registry:ui",
"content": "// Vendor's button implementation\nexport function Button() { ... }"
}
],
"cssVars": {
"light": {
"--button-bg": "blue"
}
}
}
```
**2. Create your custom override** (`@my-company/custom-button`):
```json title="custom-button.json" showLineNumbers
{
"name": "custom-button",
"type": "registry:ui",
"registryDependencies": [
"@vendor/button" // Import original first
],
"cssVars": {
"light": {
"--button-bg": "purple" // Override the color
}
}
}
```
**3. Install your custom version**:
```bash
npx shadcn@beta add @my-company/custom-button
```
This installs the original button from `@vendor/button` and then overrides the `cssVars` with your own custom values.
### Advanced Override Patterns
#### Extending Without Replacing
Keep the original and add extensions:
```json title="extended-table.json" showLineNumbers
{
"name": "extended-table",
"registryDependencies": ["@vendor/table"],
"files": [
{
"path": "components/ui/table-extended.tsx",
"content": "import { Table } from '@vendor/table'\n// Add your extensions\nexport function ExtendedTable() { ... }"
}
]
}
```
This will install the original table from `@vendor/table` and then add your extensions to `components/ui/table-extended.tsx`.
#### Partial Override (Multi-file Resources)
Override only specific files from a complex component:
```json title="custom-auth.json" showLineNumbers
{
"name": "custom-auth",
"registryDependencies": [
"@vendor/auth" // Has multiple files
],
"files": [
{
"path": "lib/auth-server.ts",
"type": "registry:lib",
"content": "// Your custom auth server"
}
]
}
```
### Resolution Order Example
When you install `@custom/dashboard` that depends on multiple resources:
```json title="dashboard.json" showLineNumbers
{
"name": "dashboard",
"registryDependencies": [
"@shadcn/card", // 1. Resolved first
"@vendor/chart", // 2. Resolved second
"@custom/card" // 3. Resolved last (overrides @shadcn/card)
]
}
```
Resolution order:
1. `@shadcn/card` - installs to `components/ui/card.tsx`
2. `@vendor/chart` - installs to `components/ui/chart.tsx`
3. `@custom/card` - overwrites `components/ui/card.tsx` (if same target)
### Key Resolution Features
1. **Source Tracking**: Each resource knows which registry it came from, avoiding naming conflicts
2. **Circular Dependency Prevention**: Automatically detects and prevents circular dependencies
3. **Smart Installation Order**: Dependencies are installed first, then the resources that use them
We intentionally designed the namespace system to be decentralized. There is no central registrar for namespaces. You are free to create and use any namespace you want.
This decentralized approach gives you complete flexibility to organize your resources however makes sense for your organization.
You can create multiple registries for different purposes:
```json title="components.json" showLineNumbers
{
"registries": {
"@acme-ui": "https://registry.acme.com/ui/{name}.json",
"@acme-docs": "https://registry.acme.com/docs/{name}.json",
"@acme-ai": "https://registry.acme.com/ai/{name}.json",
"@acme-themes": "https://registry.acme.com/themes/{name}.json",
"@acme-internal": {
"url": "https://internal.acme.com/registry/{name}.json",
"headers": {
"Authorization": "Bearer ${INTERNAL_TOKEN}"
}
}
}
}
```
This allows you to:
- **Organize by type**: Separate UI components, documentation, AI resources, etc.
- **Organize by team**: Different teams can maintain their own registries
- **Organize by visibility**: Public vs. private resources
- **Organize by version**: Stable vs. experimental registries
- **No naming conflicts**: Since there's no central authority, you don't need to worry about namespace collisions
### Examples of Multi-Registry Setups
#### By Resource Type
```json title="components.json" showLineNumbers
{
"@components": "https://cdn.company.com/components/{name}.json",
"@hooks": "https://cdn.company.com/hooks/{name}.json",
"@utils": "https://cdn.company.com/utils/{name}.json",
"@prompts": "https://cdn.company.com/ai-prompts/{name}.json"
}
```
#### By Team or Department
```json
{
"@design": "https://design.company.com/registry/{name}.json",
"@engineering": "https://eng.company.com/registry/{name}.json",
"@marketing": "https://marketing.company.com/registry/{name}.json"
}
```
#### By Stability
```json title="components.json" showLineNumbers
{
"@stable": "https://registry.company.com/stable/{name}.json",
"@latest": "https://registry.company.com/beta/{name}.json",
"@experimental": "https://registry.company.com/experimental/{name}.json"
}
```
## Built-in Registries
The `@shadcn` namespace is built-in and always available:
```bash
npx shadcn@beta add @shadcn/button
```
This is equivalent to installing from the default shadcn/ui registry.
## Versioning
You can implement versioning for your registry resources using query parameters. This allows users to pin specific versions or use different release channels.
### Basic Version Parameter
```json title="components.json" showLineNumbers
{
"@versioned": {
"url": "https://registry.example.com/{name}",
"params": {
"version": "v2"
}
}
}
```
This resolves `@versioned/button` to: `https://registry.example.com/button?version=v2`
### Dynamic Version Selection
Use environment variables to control versions across your project:
```json title="components.json" showLineNumbers
{
"@stable": {
"url": "https://registry.company.com/{name}",
"params": {
"version": "${REGISTRY_VERSION}"
}
}
}
```
This allows you to:
- Set `REGISTRY_VERSION=v1.2.3` in production
- Override per environment (dev, staging, prod)
### Semantic Versioning
Implement semantic versioning with range support:
```json title="components.json" showLineNumbers
{
"@npm-style": {
"url": "https://registry.example.com/{name}",
"params": {
"semver": "^2.0.0",
"prerelease": "${ALLOW_PRERELEASE}"
}
}
}
```
### Version Resolution Best Practices
1. **Use environment variables** for version control across environments
2. **Provide sensible defaults** using the `${VAR:-default}` syntax
3. **Document version schemes** clearly for registry users
4. **Support version pinning** for reproducible builds
5. **Implement version discovery** endpoints (e.g., `/versions/{name}`)
6. **Cache versioned resources** appropriately with proper cache headers
## CLI Commands
The shadcn CLI provides several commands for working with namespaced registries:
### Adding Resources
Install resources from any configured registry:
```bash
# Install from a specific registry
npx shadcn@beta add @v0/dashboard
# Install multiple resources
npx shadcn@beta add @acme/button @lib/utils @ai/prompt
# Install from URL directly
npx shadcn@beta add https://registry.example.com/button.json
# Install from local file
npx shadcn@beta add ./local-registry/button.json
```
### Viewing Resources
Inspect registry items before installation:
```bash
# View a resource from a registry
npx shadcn@beta view @acme/button
# View multiple resources
npx shadcn@beta view @v0/dashboard @shadcn/card
# View from URL
npx shadcn@beta view https://registry.example.com/button.json
```
The `view` command displays:
- Resource metadata (name, type, description)
- Dependencies and registry dependencies
- File contents that will be installed
- CSS variables and Tailwind configuration
- Required environment variables
### Searching Registries
Search for available resources in registries:
```bash
# Search a specific registry
npx shadcn@beta search @v0
# Search with query
npx shadcn@beta search @acme --query "auth"
# Search multiple registries
npx shadcn@beta search @v0 @acme @lib
# Limit results
npx shadcn@beta search @v0 --limit 10 --offset 20
# List all items (alias for search)
npx shadcn@beta list @acme
```
Search results include:
- Resource name and type
- Description
- Registry source
## Error Handling
### Registry Not Configured
If you reference a registry that isn't configured:
```bash
npx shadcn@beta add @non-existent/component
```
Error:
```txt
Unknown registry "@non-existent". Make sure it is defined in components.json as follows:
{
"registries": {
"@non-existent": "[URL_TO_REGISTRY]"
}
}
```
### Missing Environment Variables
If required environment variables are not set:
```txt
Registry "@private" requires the following environment variables:
• REGISTRY_TOKEN
Set the required environment variables to your .env or .env.local file.
```
### Resource Not Found
404 Not Found:
```txt
The item at https://registry.company.com/button.json was not found. It may not exist at the registry.
```
This usually means:
- The resource name is misspelled
- The resource doesn't exist in the registry
- The registry URL pattern is incorrect
### Authentication Failures
401 Unauthorized:
```txt
You are not authorized to access the item at https://api.company.com/button.json
Check your authentication credentials and environment variables.
```
403 Forbidden:
```txt
Access forbidden for https://api.company.com/button.json
Verify your API key has the necessary permissions.
```
## Creating Your Own Registry
To make your registry compatible with the namespace system, you can serve any type of resource - components, libraries, utilities, AI prompts, themes, configurations, or any other shareable code/content:
1. **Implement the registry item schema**: Your registry must return JSON that conforms to the [registry item schema](/docs/registry/registry-item-json).
2. **Support the URL pattern**: Include `{name}` in your URL template where the resource name will be inserted.
3. **Define resource types**: Use appropriate `type` fields to identify your resources (e.g., `registry:ui`, `registry:lib`, `registry:ai`, `registry:theme`, etc.).
4. **Handle authentication** (if needed): Accept authentication via headers or query parameters.
5. **Document your namespace**: Provide clear instructions for users to configure your registry:
```json title="components.json" showLineNumbers
{
"registries": {
"@your-registry": "https://your-domain.com/r/{name}.json"
}
}
```
## Technical Details
### Parser Pattern
The namespace parser uses the following regex pattern:
```regex title="namespace-parser.js"
/^(@[a-zA-Z0-9](?:[a-zA-Z0-9-_]*[a-zA-Z0-9])?)\/(.+)$/
```
This ensures valid namespace formatting and proper component name extraction.
### Resolution Process
1. **Parse**: Extract namespace and component name from `@namespace/component`
2. **Lookup**: Find registry configuration for `@namespace`
3. **Build URL**: Replace placeholders with actual values
4. **Set Headers**: Apply authentication headers if configured
5. **Fetch**: Retrieve component from the resolved URL
6. **Validate**: Ensure response matches registry item schema
7. **Resolve Dependencies**: Recursively fetch any registry dependencies
### Cross-Registry Dependencies
When a component has dependencies from different registries, the resolver:
1. Maintains separate authentication contexts for each registry
2. Resolves each dependency from its respective source
3. Deduplicates files based on target paths
4. Merges configurations (tailwind, cssVars, etc.) from all sources
## Best Practices
1. **Use environment variables** for sensitive data like API keys and tokens
2. **Namespace your registry** with a unique, descriptive name
3. **Document authentication requirements** clearly for users
4. **Implement proper error responses** with helpful messages
5. **Cache registry responses** when possible to improve performance
6. **Support style variants** if your components have multiple themes
## Troubleshooting
### Resources not found
- Verify the registry URL is correct and accessible
- Check that the `{name}` placeholder is included in the URL
- Ensure the resource exists in the registry
- Confirm the resource type matches what the registry provides
### Authentication issues
- Confirm environment variables are set correctly
- Verify API keys/tokens are valid and not expired
- Check that headers are being sent in the correct format
### Dependency conflicts
- Review resources with the same name from different registries
- Use fully qualified names (`@namespace/resource`) to avoid ambiguity
- Check for circular dependencies between registries
- Ensure resource types are compatible when mixing registries

View File

@@ -8,8 +8,8 @@ If your registry is hosted and publicly accessible via a URL, you can open a reg
eg. [https://v0.dev/chat/api/open?url=https://ui.shadcn.com/r/styles/new-york/login-01.json](https://v0.dev/chat/api/open?url=https://ui.shadcn.com/r/styles/new-york/login-01.json)
<Callout className="mt-6">
**Note:** The `Open in v0` button does not support `cssVars` and `tailwind`
properties.
**Important:** `Open in v0` does not support `cssVars`, `css`, `envVars`,
namespaced registries, or advanced authentication methods.
</Callout>
## Button
@@ -61,4 +61,46 @@ export function OpenInV0Button({ url }: { url: string }) {
## Authentication
See the [Adding Auth](/docs/registry/getting-started#adding-auth) section for more information on how to authenticate requests to your registry and Open in v0.
Open in v0 only supports query parameter authentication. It does not support namespaced registries or advanced authentication methods like Bearer tokens or API keys in headers.
### Using Query Parameter Authentication
To add authentication to your registry for Open in v0, use a `token` query parameter:
```
https://registry.company.com/r/hello-world.json?token=your_secure_token_here
```
When implementing this on your registry server:
1. Check for the `token` query parameter
2. Validate the token against your authentication system
3. Return a `401 Unauthorized` response if the token is invalid or missing
4. Both the shadcn CLI and Open in v0 will handle the 401 response and display an appropriate message to users
### Example Implementation
```typescript
// Next.js API route example
export async function GET(request: NextRequest) {
const token = request.nextUrl.searchParams.get('token')
if (!isValidToken(token)) {
return NextResponse.json(
{
error: "Unauthorized",
message: "Invalid or missing token"
},
{ status: 401 }
)
}
// Return the registry item
return NextResponse.json(registryItem)
}
```
<Callout className="mt-6">
**Security Note:** Make sure to encrypt and expire tokens. Never expose
production tokens in documentation or examples.
</Callout>

View File

@@ -12,6 +12,12 @@ The `registry-item.json` schema is used to define your custom registry items.
"type": "registry:block",
"title": "Hello World",
"description": "A simple hello world component.",
"registryDependencies": [
"button",
"@acme/input-form",
"https://example.com/r/foo"
],
"dependencies": ["is-even@3.0.0", "motion"],
"files": [
{
"path": "registry/new-york/hello-world/hello-world.tsx",
@@ -140,17 +146,17 @@ Use `@version` to specify the version of your registry item.
### registryDependencies
Used for registry dependencies. Can be names or URLs. Use the name of the item to reference shadcn/ui components and urls to reference other registries.
Used for registry dependencies. Can be names, namespaced or URLs.
- For `shadcn/ui` registry items such as `button`, `input`, `select`, etc use the name eg. `['button', 'input', 'select']`.
- For namespaced registry items such as `@acme` use the name eg. `['@acme/input-form']`.
- For custom registry items use the URL of the registry item eg. `['https://example.com/r/hello-world.json']`.
```json title="registry-item.json" showLineNumbers
{
"registryDependencies": [
"button",
"input",
"select",
"@acme/input-form",
"https://example.com/r/editor.json"
]
}

View File

@@ -16,6 +16,12 @@ The `registry.json` schema is used to define your custom component registry.
"type": "registry:block",
"title": "Hello World",
"description": "A simple hello world component.",
"registryDependencies": [
"button",
"@acme/input-form",
"https://example.com/r/foo"
],
"dependencies": ["is-even@3.0.0", "motion"],
"files": [
{
"path": "registry/new-york/hello-world/hello-world.tsx",
@@ -73,6 +79,12 @@ The `items` in your registry. Each item must implement the [registry-item schema
"type": "registry:block",
"title": "Hello World",
"description": "A simple hello world component.",
"registryDependencies": [
"button",
"@acme/input-form",
"https://example.com/r/foo"
],
"dependencies": ["is-even@3.0.0", "motion"],
"files": [
{
"path": "registry/new-york/hello-world/hello-world.tsx",

View File

@@ -52,7 +52,7 @@ export const mdxComponents = {
.replace(/\?/g, "")
.toLowerCase()}
className={cn(
"font-heading mt-12 scroll-m-28 text-2xl font-medium tracking-tight first:mt-0 lg:mt-20 [&+p]:!mt-4 *:[code]:text-2xl",
"font-heading mt-8 scroll-m-28 text-2xl font-medium tracking-tight first:mt-0 lg:mt-8 [&+p]:!mt-4 *:[code]:text-2xl",
className
)}
{...props}
@@ -62,7 +62,7 @@ export const mdxComponents = {
h3: ({ className, ...props }: React.ComponentProps<"h3">) => (
<h3
className={cn(
"font-heading mt-8 scroll-m-28 text-xl font-semibold tracking-tight *:[code]:text-xl",
"font-heading mt-8 scroll-m-28 text-xl font-medium tracking-tight *:[code]:text-xl",
className
)}
{...props}
@@ -228,7 +228,7 @@ export const mdxComponents = {
return (
<code
className={cn(
"bg-muted relative rounded-md px-[0.3rem] py-[0.2rem] font-mono text-[0.8rem] outline-none",
"bg-muted relative rounded-md px-[0.3rem] py-[0.2rem] font-mono text-[0.8rem] break-words outline-none",
className
)}
{...props}
@@ -310,7 +310,7 @@ export const mdxComponents = {
}: React.ComponentProps<typeof TabsTrigger>) => (
<TabsTrigger
className={cn(
"text-muted-foreground data-[state=active]:text-foreground px-0 text-base data-[state=active]:shadow-none dark:data-[state=active]:border-transparent dark:data-[state=active]:bg-transparent",
"text-muted-foreground data-[state=active]:text-foreground data-[state=active]:border-primary dark:data-[state=active]:border-primary rounded-none border-0 border-b-2 border-transparent bg-transparent px-0 pb-3 text-base data-[state=active]:bg-transparent data-[state=active]:shadow-none dark:data-[state=active]:bg-transparent",
className
)}
{...props}

View File

@@ -73,6 +73,11 @@ const nextConfig = {
destination: "/docs/:path*.md",
permanent: true,
},
{
source: "/mcp",
destination: "/docs/mcp",
permanent: false,
},
]
},
rewrites() {

View File

@@ -1,13 +1,82 @@
import { promises as fs } from "fs"
import path from "path"
import { server } from "@/src/mcp"
import { loadEnvFiles } from "@/src/utils/env-loader"
import { getConfig } from "@/src/utils/get-config"
import { getPackageManager } from "@/src/utils/get-package-manager"
import { handleError } from "@/src/utils/handle-error"
import { logger } from "@/src/utils/logger"
import { spinner } from "@/src/utils/spinner"
import { updateDependencies } from "@/src/utils/updaters/update-dependencies"
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"
import { Command } from "commander"
import deepmerge from "deepmerge"
import { execa } from "execa"
import fsExtra from "fs-extra"
import prompts from "prompts"
import z from "zod"
const SHADCN_MCP_VERSION = "beta"
const CLIENTS = [
{
name: "claude",
label: "Claude Code",
configPath: ".mcp.json",
config: {
mcpServers: {
shadcn: {
command: "npx",
args: [`shadcn@${SHADCN_MCP_VERSION}`, "mcp"],
},
},
},
},
{
name: "cursor",
label: "Cursor",
configPath: ".cursor/mcp.json",
config: {
mcpServers: {
shadcn: {
command: "npx",
args: [`shadcn@${SHADCN_MCP_VERSION}`, "mcp"],
},
},
},
},
{
name: "vscode",
label: "VS Code",
configPath: ".vscode/mcp.json",
config: {
servers: {
shadcn: {
command: "npx",
args: [`shadcn@${SHADCN_MCP_VERSION}`, "mcp"],
},
},
},
},
// {
// name: "zed",
// label: "Zed Editor",
// configPath: ".zed/settings.json",
// config: {
// context_servers: {
// shadcn: {
// source: "custom",
// command: "npx",
// args: [`shadcn@${SHADCN_MCP_VERSION}`, "mcp"],
// },
// },
// },
// },
] as const
export const mcp = new Command()
.name("mcp")
.description("starts the registry MCP server")
.description("MCP server and configuration commands")
.option(
"-c, --cwd <cwd>",
"the working directory. defaults to the current directory.",
@@ -23,3 +92,115 @@ export const mcp = new Command()
handleError(error)
}
})
const mcpInitOptionsSchema = z.object({
client: z.enum(["claude", "cursor", "vscode", "zed"]),
cwd: z.string(),
})
mcp
.command("init")
.description("Initialize MCP configuration for your client")
.option(
"--client <client>",
`MCP client (${CLIENTS.map((c) => c.name).join(", ")})`
)
.action(async (opts, command) => {
try {
// Get the cwd from parent command
const parentOpts = command.parent?.opts() || {}
const cwd = parentOpts.cwd || process.cwd()
let client = opts.client
if (!client) {
const response = await prompts({
type: "select",
name: "client",
message: "Which MCP client are you using?",
choices: CLIENTS.map((c) => ({
title: c.label,
value: c.name,
})),
})
if (!response.client) {
logger.break()
process.exit(1)
}
client = response.client
}
const options = mcpInitOptionsSchema.parse({
client,
cwd,
})
const configSpinner = spinner("Configuring MCP server...").start()
const configPath = await runMcpInit(options)
configSpinner.succeed("Configuring MCP server.")
const config = await getConfig(options.cwd)
if (config) {
await updateDependencies([], ["shadcn"], config, {
silent: false,
})
} else {
const packageManager = await getPackageManager(options.cwd)
const installCommand = packageManager === "npm" ? "install" : "add"
const devFlag = packageManager === "npm" ? "--save-dev" : "-D"
const installSpinner = spinner("Installing dependencies...").start()
await execa(packageManager, [installCommand, devFlag, "shadcn"], {
cwd: options.cwd,
})
installSpinner.succeed("Installing dependencies.")
}
logger.break()
logger.success(`Configuration saved to ${configPath}.`)
logger.break()
} catch (error) {
handleError(error)
}
})
const overwriteMerge = (_: any[], sourceArray: any[]) => sourceArray
async function runMcpInit(options: z.infer<typeof mcpInitOptionsSchema>) {
const { client, cwd } = options
const clientInfo = CLIENTS.find((c) => c.name === client)
if (!clientInfo) {
throw new Error(
`Unknown client: ${client}. Available clients: ${CLIENTS.map(
(c) => c.name
).join(", ")}`
)
}
const configPath = path.join(cwd, clientInfo.configPath)
let existingConfig = {}
try {
const content = await fs.readFile(configPath, "utf-8")
existingConfig = JSON.parse(content)
} catch {}
const mergedConfig = deepmerge(
existingConfig,
clientInfo.config as Record<string, unknown>,
{ arrayMerge: overwriteMerge }
)
const dir = path.dirname(configPath)
await fsExtra.ensureDir(dir)
await fs.writeFile(
configPath,
JSON.stringify(mergedConfig, null, 2) + "\n",
"utf-8"
)
return clientInfo.configPath
}