``` ├── .env.example ├── .gitignore ├── LICENSE ├── README.md ├── ai/ ├── providers.ts ├── app/ ├── actions.ts ├── api/ ├── chat/ ├── route.ts ├── chats/ ├── [id]/ ├── route.ts ├── route.ts ├── chat/ ├── [id]/ ├── page.tsx ├── favicon.ico ├── globals.css ├── layout.tsx ├── opengraph-image.png ├── page.tsx ├── providers.tsx ├── twitter-image.png ├── components.json ├── components/ ├── api-key-manager.tsx ├── chat-sidebar.tsx ├── chat.tsx ├── copy-button.tsx ├── deploy-button.tsx ├── icons.tsx ├── input.tsx ├── markdown.tsx ├── mcp-server-manager.tsx ├── message.tsx ├── messages.tsx ├── model-picker.tsx ├── project-overview.tsx ├── suggested-prompts.tsx ├── textarea.tsx ├── theme-provider.tsx ├── theme-toggle.tsx ├── tool-invocation.tsx ├── ui/ ├── accordion.tsx ├── avatar.tsx ├── badge.tsx ├── button.tsx ├── dialog.tsx ├── dropdown-menu.tsx ├── input.tsx ├── label.tsx ├── popover.tsx ├── scroll-area.tsx ├── select.tsx ├── separator.tsx ├── sheet.tsx ├── sidebar.tsx ├── skeleton.tsx ├── sonner.tsx ├── text-morph.tsx ├── textarea.tsx ├── tooltip.tsx ├── drizzle.config.ts ├── drizzle/ ├── 0000_supreme_rocket_raccoon.sql ├── 0001_curious_paper_doll.sql ├── 0002_free_cobalt_man.sql ├── 0003_oval_energizer.sql ├── 0004_tense_ricochet.sql ├── 0005_early_payback.sql ├── meta/ ├── 0000_snapshot.json ``` ## /.env.example ```example path="/.env.example" XAI_API_KEY="" OPENAI_API_KEY= DATABASE_URL="postgresql://username:password@host:port/database" ``` ## /.gitignore ```gitignore path="/.gitignore" # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. # dependencies /node_modules /.pnp .pnp.* .yarn/* !.yarn/patches !.yarn/plugins !.yarn/releases !.yarn/versions # testing /coverage # next.js /.next/ /out/ # production /build # misc .DS_Store *.pem # debug npm-debug.log* yarn-debug.log* yarn-error.log* .pnpm-debug.log* # env files (can opt-in for committing if needed) .env.local .env # vercel .vercel # typescript *.tsbuildinfo next-env.d.ts ``` ## /LICENSE ``` path="/LICENSE" Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS Copyright 2025 Zaid Mukaddam Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ``` ## /README.md

Scira MCP Chat

An open-source AI chatbot app powered by Model Context Protocol (MCP), built with Next.js and the AI SDK by Vercel.

FeaturesMCP ConfigurationLicense


## Features - Streaming text responses powered by the [AI SDK by Vercel](https://sdk.vercel.ai/docs), allowing multiple AI providers to be used interchangeably with just a few lines of code. - Full integration with [Model Context Protocol (MCP)](https://modelcontextprotocol.io) servers to expand available tools and capabilities. - Multiple MCP transport types (SSE and stdio) for connecting to various tool providers. - Built-in tool integration for extending AI capabilities. - Reasoning model support. - [shadcn/ui](https://ui.shadcn.com/) components for a modern, responsive UI powered by [Tailwind CSS](https://tailwindcss.com). - Built with the latest [Next.js](https://nextjs.org) App Router. ## MCP Server Configuration This application supports connecting to Model Context Protocol (MCP) servers to access their tools. You can add and manage MCP servers through the settings icon in the chat interface. ### Adding an MCP Server 1. Click the settings icon (⚙️) next to the model selector in the chat interface. 2. Enter a name for your MCP server. 3. Select the transport type: - **SSE (Server-Sent Events)**: For HTTP-based remote servers - **stdio (Standard I/O)**: For local servers running on the same machine #### SSE Configuration If you select SSE transport: 1. Enter the server URL (e.g., `https://mcp.example.com/token/sse`) 2. Click "Add Server" #### stdio Configuration If you select stdio transport: 1. Enter the command to execute (e.g., `npx`) 2. Enter the command arguments (e.g., `-y @modelcontextprotocol/server-google-maps`) - You can enter space-separated arguments or paste a JSON array 3. Click "Add Server" 4. Click "Use" to activate the server for the current chat session. ### Available MCP Servers You can use any MCP-compatible server with this application. Here are some examples: - [Composio](https://composio.dev/mcp) - Provides search, code interpreter, and other tools - [Zapier MCP](https://zapier.com/mcp) - Provides access to Zapier tools - Any MCP server using stdio transport with npx and python3 ## License This project is licensed under the Apache License 2.0 - see the [LICENSE](LICENSE) file for details. ## /ai/providers.ts ```ts path="/ai/providers.ts" import { createOpenAI } from "@ai-sdk/openai"; import { createGroq } from "@ai-sdk/groq"; import { createAnthropic } from "@ai-sdk/anthropic"; import { createXai } from "@ai-sdk/xai"; import { customProvider, wrapLanguageModel, extractReasoningMiddleware } from "ai"; export interface ModelInfo { provider: string; name: string; description: string; apiVersion: string; capabilities: string[]; } const middleware = extractReasoningMiddleware({ tagName: 'think', }); // Helper to get API keys from environment variables first, then localStorage const getApiKey = (key: string): string | undefined => { // Check for environment variables first if (process.env[key]) { return process.env[key] || undefined; } // Fall back to localStorage if available if (typeof window !== 'undefined') { return window.localStorage.getItem(key) || undefined; } return undefined; }; // Create provider instances with API keys from localStorage const openaiClient = createOpenAI({ apiKey: getApiKey('OPENAI_API_KEY'), }); const anthropicClient = createAnthropic({ apiKey: getApiKey('ANTHROPIC_API_KEY'), }); const groqClient = createGroq({ apiKey: getApiKey('GROQ_API_KEY'), }); const xaiClient = createXai({ apiKey: getApiKey('XAI_API_KEY'), }); const languageModels = { "gpt-4.1-mini": openaiClient("gpt-4.1-mini"), "claude-3-7-sonnet": anthropicClient('claude-3-7-sonnet-20250219'), "qwen-qwq": wrapLanguageModel( { model: groqClient("qwen-qwq-32b"), middleware } ), "grok-3-mini": xaiClient("grok-3-mini-latest"), }; export const modelDetails: Record = { "gpt-4.1-mini": { provider: "OpenAI", name: "GPT-4.1 Mini", description: "Compact version of OpenAI's GPT-4.1 with good balance of capabilities, including vision.", apiVersion: "gpt-4.1-mini", capabilities: ["Balance", "Creative", "Vision"] }, "claude-3-7-sonnet": { provider: "Anthropic", name: "Claude 3.7 Sonnet", description: "Latest version of Anthropic's Claude 3.7 Sonnet with strong reasoning and coding capabilities.", apiVersion: "claude-3-7-sonnet-20250219", capabilities: ["Reasoning", "Efficient", "Agentic"] }, "qwen-qwq": { provider: "Groq", name: "Qwen QWQ", description: "Latest version of Alibaba's Qwen QWQ with strong reasoning and coding capabilities.", apiVersion: "qwen-qwq", capabilities: ["Reasoning", "Efficient", "Agentic"] }, "grok-3-mini": { provider: "XAI", name: "Grok 3 Mini", description: "Latest version of XAI's Grok 3 Mini with strong reasoning and coding capabilities.", apiVersion: "grok-3-mini-latest", capabilities: ["Reasoning", "Efficient", "Agentic"] }, }; // Update API keys when localStorage changes (for runtime updates) if (typeof window !== 'undefined') { window.addEventListener('storage', (event) => { // Reload the page if any API key changed to refresh the providers if (event.key?.includes('API_KEY')) { window.location.reload(); } }); } export const model = customProvider({ languageModels, }); export type modelID = keyof typeof languageModels; export const MODELS = Object.keys(languageModels); export const defaultModel: modelID = "qwen-qwq"; ``` ## /app/actions.ts ```ts path="/app/actions.ts" "use server"; import { openai } from "@ai-sdk/openai"; import { generateObject } from "ai"; import { z } from "zod"; // Helper to extract text content from a message regardless of format function getMessageText(message: any): string { // Check if the message has parts (new format) if (message.parts && Array.isArray(message.parts)) { const textParts = message.parts.filter((p: any) => p.type === 'text' && p.text); if (textParts.length > 0) { return textParts.map((p: any) => p.text).join('\n'); } } // Fallback to content (old format) if (typeof message.content === 'string') { return message.content; } // If content is an array (potentially of parts), try to extract text if (Array.isArray(message.content)) { const textItems = message.content.filter((item: any) => typeof item === 'string' || (item.type === 'text' && item.text) ); if (textItems.length > 0) { return textItems.map((item: any) => typeof item === 'string' ? item : item.text ).join('\n'); } } return ''; } export async function generateTitle(messages: any[]) { // Convert messages to a format that OpenAI can understand const normalizedMessages = messages.map(msg => ({ role: msg.role, content: getMessageText(msg) })); const { object } = await generateObject({ model: openai("gpt-4.1"), schema: z.object({ title: z.string().min(1).max(100), }), system: ` You are a helpful assistant that generates titles for chat conversations. The title should be a short description of the conversation. The title should be no more than 30 characters. The title should be unique and not generic. `, messages: [ ...normalizedMessages, { role: "user", content: "Generate a title for the conversation.", }, ], }); return object.title; } ``` ## /app/api/chat/route.ts ```ts path="/app/api/chat/route.ts" import { model, type modelID } from "@/ai/providers"; import { streamText, type UIMessage } from "ai"; import { appendResponseMessages } from 'ai'; import { saveChat, saveMessages, convertToDBMessages } from '@/lib/chat-store'; import { nanoid } from 'nanoid'; import { db } from '@/lib/db'; import { chats } from '@/lib/db/schema'; import { eq, and } from 'drizzle-orm'; import { experimental_createMCPClient as createMCPClient, MCPTransport } from 'ai'; import { Experimental_StdioMCPTransport as StdioMCPTransport } from 'ai/mcp-stdio'; import { spawn } from "child_process"; // Allow streaming responses up to 30 seconds export const maxDuration = 120; interface KeyValuePair { key: string; value: string; } interface MCPServerConfig { url: string; type: 'sse' | 'stdio'; command?: string; args?: string[]; env?: KeyValuePair[]; headers?: KeyValuePair[]; } export async function POST(req: Request) { const { messages, chatId, selectedModel, userId, mcpServers = [], }: { messages: UIMessage[]; chatId?: string; selectedModel: modelID; userId: string; mcpServers?: MCPServerConfig[]; } = await req.json(); if (!userId) { return new Response( JSON.stringify({ error: "User ID is required" }), { status: 400, headers: { "Content-Type": "application/json" } } ); } const id = chatId || nanoid(); // Check if chat already exists for the given ID // If not, we'll create it in onFinish let isNewChat = false; if (chatId) { try { const existingChat = await db.query.chats.findFirst({ where: and( eq(chats.id, chatId), eq(chats.userId, userId) ) }); isNewChat = !existingChat; } catch (error) { console.error("Error checking for existing chat:", error); // Continue anyway, we'll create the chat in onFinish isNewChat = true; } } else { // No ID provided, definitely new isNewChat = true; } // Initialize tools let tools = {}; const mcpClients: any[] = []; // Process each MCP server configuration for (const mcpServer of mcpServers) { try { // Create appropriate transport based on type let transport: MCPTransport | { type: 'sse', url: string, headers?: Record }; if (mcpServer.type === 'sse') { // Convert headers array to object for SSE transport const headers: Record = {}; if (mcpServer.headers && mcpServer.headers.length > 0) { mcpServer.headers.forEach(header => { if (header.key) headers[header.key] = header.value || ''; }); } transport = { type: 'sse' as const, url: mcpServer.url, headers: Object.keys(headers).length > 0 ? headers : undefined }; } else if (mcpServer.type === 'stdio') { // For stdio transport, we need command and args if (!mcpServer.command || !mcpServer.args || mcpServer.args.length === 0) { console.warn("Skipping stdio MCP server due to missing command or args"); continue; } // Convert env array to object for stdio transport const env: Record = {}; if (mcpServer.env && mcpServer.env.length > 0) { mcpServer.env.forEach(envVar => { if (envVar.key) env[envVar.key] = envVar.value || ''; }); } // Check for uvx pattern and transform to python3 -m uv run if (mcpServer.command === 'uvx') { // install uv const subprocess = spawn('pip3', ['install', 'uv']); subprocess.on('close', (code: number) => { if (code !== 0) { console.error(`Failed to install uv: ${code}`); } }); // wait for the subprocess to finish await new Promise((resolve) => { subprocess.on('close', resolve); console.log("installed uv"); }); console.log("Detected uvx pattern, transforming to python3 -m uv run"); mcpServer.command = 'python3'; // Get the tool name (first argument) const toolName = mcpServer.args[0]; // Replace args with the new pattern mcpServer.args = ['-m', 'uv', 'run', toolName, ...mcpServer.args.slice(1)]; } // if python is passed in the command, install the python package mentioned in args after -m with subprocess or use regex to find the package name else if (mcpServer.command.includes('python3')) { const packageName = mcpServer.args[mcpServer.args.indexOf('-m') + 1]; console.log("installing python package", packageName); const subprocess = spawn('pip3', ['install', packageName]); subprocess.on('close', (code: number) => { if (code !== 0) { console.error(`Failed to install python package: ${code}`); } }); // wait for the subprocess to finish await new Promise((resolve) => { subprocess.on('close', resolve); console.log("installed python package", packageName); }); } transport = new StdioMCPTransport({ command: mcpServer.command, args: mcpServer.args, env: Object.keys(env).length > 0 ? env : undefined }); } else { console.warn(`Skipping MCP server with unsupported transport type: ${mcpServer.type}`); continue; } const mcpClient = await createMCPClient({ transport }); mcpClients.push(mcpClient); const mcptools = await mcpClient.tools(); console.log(`MCP tools from ${mcpServer.type} transport:`, Object.keys(mcptools)); // Add MCP tools to tools object tools = { ...tools, ...mcptools }; } catch (error) { console.error("Failed to initialize MCP client:", error); // Continue with other servers instead of failing the entire request } } // Register cleanup for all clients if (mcpClients.length > 0) { req.signal.addEventListener('abort', async () => { for (const client of mcpClients) { try { await client.close(); } catch (error) { console.error("Error closing MCP client:", error); } } }); } console.log("messages", messages); console.log("parts", messages.map(m => m.parts.map(p => p))); // If there was an error setting up MCP clients but we at least have composio tools, continue const result = streamText({ model: model.languageModel(selectedModel), system: `You are a helpful assistant with access to a variety of tools. Today's date is ${new Date().toISOString().split('T')[0]}. The tools are very powerful, and you can use them to answer the user's question. So choose the tool that is most relevant to the user's question. If tools are not available, say you don't know or if the user wants a tool they can add one from the server icon in bottom left corner in the sidebar. You can use multiple tools in a single response. Always respond after using the tools for better user experience. You can run multiple steps using all the tools!!!! Make sure to use the right tool to respond to the user's question. Multiple tools can be used in a single response and multiple steps can be used to answer the user's question. ## Response Format - Markdown is supported. - Respond according to tool's response. - Use the tools to answer the user's question. - If you don't know the answer, use the tools to find the answer or say you don't know. `, messages, tools, maxSteps: 20, providerOptions: { google: { thinkingConfig: { thinkingBudget: 2048, }, }, anthropic: { thinking: { type: 'enabled', budgetTokens: 12000 }, } }, onError: (error) => { console.error(JSON.stringify(error, null, 2)); }, async onFinish({ response }) { const allMessages = appendResponseMessages({ messages, responseMessages: response.messages, }); await saveChat({ id, userId, messages: allMessages, }); const dbMessages = convertToDBMessages(allMessages, id); await saveMessages({ messages: dbMessages }); // close all mcp clients // for (const client of mcpClients) { // await client.close(); // } } }); result.consumeStream() return result.toDataStreamResponse({ sendReasoning: true, getErrorMessage: (error) => { if (error instanceof Error) { if (error.message.includes("Rate limit")) { return "Rate limit exceeded. Please try again later."; } } console.error(error); return "An error occurred."; }, }); } ``` ## /app/api/chats/[id]/route.ts ```ts path="/app/api/chats/[id]/route.ts" import { NextResponse } from "next/server"; import { getChatById, deleteChat } from "@/lib/chat-store"; interface Params { params: { id: string; }; } export async function GET(request: Request, { params }: Params) { try { const userId = request.headers.get('x-user-id'); if (!userId) { return NextResponse.json({ error: "User ID is required" }, { status: 400 }); } const { id } = await params; const chat = await getChatById(id, userId); if (!chat) { return NextResponse.json( { error: "Chat not found" }, { status: 404 } ); } return NextResponse.json(chat); } catch (error) { console.error("Error fetching chat:", error); return NextResponse.json( { error: "Failed to fetch chat" }, { status: 500 } ); } } export async function DELETE(request: Request, { params }: Params) { try { const userId = request.headers.get('x-user-id'); if (!userId) { return NextResponse.json({ error: "User ID is required" }, { status: 400 }); } const { id } = await params; await deleteChat(id, userId); return NextResponse.json({ success: true }); } catch (error) { console.error("Error deleting chat:", error); return NextResponse.json( { error: "Failed to delete chat" }, { status: 500 } ); } } ``` ## /app/api/chats/route.ts ```ts path="/app/api/chats/route.ts" import { NextResponse } from "next/server"; import { getChats } from "@/lib/chat-store"; export async function GET(request: Request) { try { const userId = request.headers.get('x-user-id'); if (!userId) { return NextResponse.json({ error: "User ID is required" }, { status: 400 }); } const chats = await getChats(userId); return NextResponse.json(chats); } catch (error) { console.error("Error fetching chats:", error); return NextResponse.json( { error: "Failed to fetch chats" }, { status: 500 } ); } } ``` ## /app/chat/[id]/page.tsx ```tsx path="/app/chat/[id]/page.tsx" "use client"; import Chat from "@/components/chat"; import { getUserId } from "@/lib/user-id"; import { useQueryClient } from "@tanstack/react-query"; import { useParams } from "next/navigation"; import { useEffect } from "react"; export default function ChatPage() { const params = useParams(); const chatId = params?.id as string; const queryClient = useQueryClient(); const userId = getUserId(); // Prefetch chat data useEffect(() => { async function prefetchChat() { if (!chatId || !userId) return; // Check if data already exists in cache const existingData = queryClient.getQueryData(['chat', chatId, userId]); if (existingData) return; // Prefetch the data await queryClient.prefetchQuery({ queryKey: ['chat', chatId, userId] as const, queryFn: async () => { try { const response = await fetch(`/api/chats/${chatId}`, { headers: { 'x-user-id': userId } }); if (!response.ok) { throw new Error('Failed to load chat'); } return response.json(); } catch (error) { console.error('Error prefetching chat:', error); return null; } }, staleTime: 1000 * 60 * 5, // 5 minutes }); } prefetchChat(); }, [chatId, userId, queryClient]); return ; } ``` ## /app/favicon.ico Binary file available at https://raw.githubusercontent.com/zaidmukaddam/scira-mcp-chat/refs/heads/main/app/favicon.ico ## /app/globals.css ```css path="/app/globals.css" @import "tailwindcss"; @plugin "tailwindcss-animate"; @custom-variant dark (&:is(.dark *)); @custom-variant sunset (&:is(.sunset *)); @custom-variant black (&:is(.black *)); :root { --background: oklch(0.99 0.01 56.32); --foreground: oklch(0.34 0.01 2.77); --card: oklch(1.00 0 0); --card-foreground: oklch(0.34 0.01 2.77); --popover: oklch(1.00 0 0); --popover-foreground: oklch(0.34 0.01 2.77); --primary: oklch(0.74 0.16 34.71); --primary-foreground: oklch(1.00 0 0); --secondary: oklch(0.96 0.02 28.90); --secondary-foreground: oklch(0.56 0.13 32.74); --muted: oklch(0.97 0.02 39.40); --muted-foreground: oklch(0.49 0.05 26.45); --accent: oklch(0.83 0.11 58.00); --accent-foreground: oklch(0.34 0.01 2.77); --destructive: oklch(0.61 0.21 22.24); --destructive-foreground: oklch(1.00 0 0); --border: oklch(0.93 0.04 38.69); --input: oklch(0.93 0.04 38.69); --ring: oklch(0.74 0.16 34.71); --chart-1: oklch(0.74 0.16 34.71); --chart-2: oklch(0.83 0.11 58.00); --chart-3: oklch(0.88 0.08 54.93); --chart-4: oklch(0.82 0.11 40.89); --chart-5: oklch(0.64 0.13 32.07); --sidebar: oklch(0.97 0.02 39.40); --sidebar-foreground: oklch(0.34 0.01 2.77); --sidebar-primary: oklch(0.74 0.16 34.71); --sidebar-primary-foreground: oklch(1.00 0 0); --sidebar-accent: oklch(0.83 0.11 58.00); --sidebar-accent-foreground: oklch(0.34 0.01 2.77); --sidebar-border: oklch(0.93 0.04 38.69); --sidebar-ring: oklch(0.74 0.16 34.71); --font-sans: Montserrat, sans-serif; --font-serif: Merriweather, serif; --font-mono: Ubuntu Mono, monospace; --radius: 0.625rem; --shadow-2xs: 0px 6px 12px -3px hsl(0 0% 0% / 0.04); --shadow-xs: 0px 6px 12px -3px hsl(0 0% 0% / 0.04); --shadow-sm: 0px 6px 12px -3px hsl(0 0% 0% / 0.09), 0px 1px 2px -4px hsl(0 0% 0% / 0.09); --shadow: 0px 6px 12px -3px hsl(0 0% 0% / 0.09), 0px 1px 2px -4px hsl(0 0% 0% / 0.09); --shadow-md: 0px 6px 12px -3px hsl(0 0% 0% / 0.09), 0px 2px 4px -4px hsl(0 0% 0% / 0.09); --shadow-lg: 0px 6px 12px -3px hsl(0 0% 0% / 0.09), 0px 4px 6px -4px hsl(0 0% 0% / 0.09); --shadow-xl: 0px 6px 12px -3px hsl(0 0% 0% / 0.09), 0px 8px 10px -4px hsl(0 0% 0% / 0.09); --shadow-2xl: 0px 6px 12px -3px hsl(0 0% 0% / 0.22); } .dark { --background: oklch(0.26 0.02 352.40); --foreground: oklch(0.94 0.01 51.32); --card: oklch(0.32 0.02 341.45); --card-foreground: oklch(0.94 0.01 51.32); --popover: oklch(0.32 0.02 341.45); --popover-foreground: oklch(0.94 0.01 51.32); --primary: oklch(0.57 0.15 35.26); --primary-foreground: oklch(1.00 0 0); --secondary: oklch(0.36 0.02 342.27); --secondary-foreground: oklch(0.94 0.01 51.32); --muted: oklch(0.32 0.02 341.45); --muted-foreground: oklch(0.84 0.02 52.63); --accent: oklch(0.83 0.11 58.00); --accent-foreground: oklch(0.26 0.02 352.40); --destructive: oklch(0.51 0.16 20.19); --destructive-foreground: oklch(1.00 0 0); --border: oklch(0.36 0.02 342.27); --input: oklch(0.36 0.02 342.27); --ring: oklch(0.74 0.16 34.71); --chart-1: oklch(0.74 0.16 34.71); --chart-2: oklch(0.83 0.11 58.00); --chart-3: oklch(0.88 0.08 54.93); --chart-4: oklch(0.82 0.11 40.89); --chart-5: oklch(0.64 0.13 32.07); --sidebar: oklch(0.26 0.02 352.40); --sidebar-foreground: oklch(0.94 0.01 51.32); --sidebar-primary: oklch(0.47 0.08 34.31); --sidebar-primary-foreground: oklch(1.00 0 0); --sidebar-accent: oklch(0.67 0.09 56.00); --sidebar-accent-foreground: oklch(0.26 0.01 353.48); --sidebar-border: oklch(0.36 0.02 342.27); --sidebar-ring: oklch(0.74 0.16 34.71); --font-sans: Montserrat, sans-serif; --font-serif: Merriweather, serif; --font-mono: Ubuntu Mono, monospace; --radius: 0.625rem; --shadow-2xs: 0px 6px 12px -3px hsl(0 0% 0% / 0.04); --shadow-xs: 0px 6px 12px -3px hsl(0 0% 0% / 0.04); --shadow-sm: 0px 6px 12px -3px hsl(0 0% 0% / 0.09), 0px 1px 2px -4px hsl(0 0% 0% / 0.09); --shadow: 0px 6px 12px -3px hsl(0 0% 0% / 0.09), 0px 1px 2px -4px hsl(0 0% 0% / 0.09); --shadow-md: 0px 6px 12px -3px hsl(0 0% 0% / 0.09), 0px 2px 4px -4px hsl(0 0% 0% / 0.09); --shadow-lg: 0px 6px 12px -3px hsl(0 0% 0% / 0.09), 0px 4px 6px -4px hsl(0 0% 0% / 0.09); --shadow-xl: 0px 6px 12px -3px hsl(0 0% 0% / 0.09), 0px 8px 10px -4px hsl(0 0% 0% / 0.09); --shadow-2xl: 0px 6px 12px -3px hsl(0 0% 0% / 0.22); } .sunset { --background: oklch(0.98 0.03 80.00); --foreground: oklch(0.34 0.01 2.77); --card: oklch(1.00 0 0); --card-foreground: oklch(0.34 0.01 2.77); --popover: oklch(1.00 0 0); --popover-foreground: oklch(0.34 0.01 2.77); --primary: oklch(0.65 0.26 34.00); --primary-foreground: oklch(1.00 0 0); --secondary: oklch(0.96 0.05 60.00); --secondary-foreground: oklch(0.56 0.13 32.74); --muted: oklch(0.97 0.02 39.40); --muted-foreground: oklch(0.49 0.05 26.45); --accent: oklch(0.83 0.22 50.00); --accent-foreground: oklch(0.34 0.01 2.77); --destructive: oklch(0.61 0.21 22.24); --destructive-foreground: oklch(1.00 0 0); --border: oklch(0.93 0.06 60.00); --input: oklch(0.93 0.06 60.00); --ring: oklch(0.65 0.26 34.00); --chart-1: oklch(0.65 0.26 34.00); --chart-2: oklch(0.83 0.22 50.00); --chart-3: oklch(0.88 0.15 54.93); --chart-4: oklch(0.82 0.20 40.89); --chart-5: oklch(0.64 0.18 32.07); --sidebar: oklch(0.97 0.04 70.00); --sidebar-foreground: oklch(0.34 0.01 2.77); --sidebar-primary: oklch(0.65 0.26 34.00); --sidebar-primary-foreground: oklch(1.00 0 0); --sidebar-accent: oklch(0.83 0.22 50.00); --sidebar-accent-foreground: oklch(0.34 0.01 2.77); --sidebar-border: oklch(0.93 0.06 60.00); --sidebar-ring: oklch(0.65 0.26 34.00); --font-sans: Montserrat, sans-serif; --font-serif: Merriweather, serif; --font-mono: Ubuntu Mono, monospace; --radius: 0.625rem; --shadow-2xs: 0px 6px 12px -3px hsl(0 0% 0% / 0.04); --shadow-xs: 0px 6px 12px -3px hsl(0 0% 0% / 0.04); --shadow-sm: 0px 6px 12px -3px hsl(0 0% 0% / 0.09), 0px 1px 2px -4px hsl(0 0% 0% / 0.09); --shadow: 0px 6px 12px -3px hsl(0 0% 0% / 0.09), 0px 1px 2px -4px hsl(0 0% 0% / 0.09); --shadow-md: 0px 6px 12px -3px hsl(0 0% 0% / 0.09), 0px 2px 4px -4px hsl(0 0% 0% / 0.09); --shadow-lg: 0px 6px 12px -3px hsl(0 0% 0% / 0.09), 0px 4px 6px -4px hsl(0 0% 0% / 0.09); --shadow-xl: 0px 6px 12px -3px hsl(0 0% 0% / 0.09), 0px 8px 10px -4px hsl(0 0% 0% / 0.09); --shadow-2xl: 0px 6px 12px -3px hsl(0 0% 0% / 0.22); } .black { --background: oklch(0.15 0.01 350.00); --foreground: oklch(0.95 0.01 60.00); --card: oklch(0.20 0.01 340.00); --card-foreground: oklch(0.95 0.01 60.00); --popover: oklch(0.20 0.01 340.00); --popover-foreground: oklch(0.95 0.01 60.00); --primary: oklch(0.45 0.10 35.00); --primary-foreground: oklch(1.00 0 0); --secondary: oklch(0.25 0.01 340.00); --secondary-foreground: oklch(0.95 0.01 60.00); --muted: oklch(0.22 0.01 340.00); --muted-foreground: oklch(0.86 0.01 60.00); --accent: oklch(0.70 0.09 58.00); --accent-foreground: oklch(0.15 0.01 350.00); --destructive: oklch(0.45 0.16 20.00); --destructive-foreground: oklch(1.00 0 0); --border: oklch(0.25 0.01 340.00); --input: oklch(0.25 0.01 340.00); --ring: oklch(0.45 0.10 35.00); --chart-1: oklch(0.45 0.10 35.00); --chart-2: oklch(0.70 0.09 58.00); --chart-3: oklch(0.80 0.06 54.00); --chart-4: oklch(0.75 0.08 40.00); --chart-5: oklch(0.55 0.10 32.00); --sidebar: oklch(0.15 0.01 350.00); --sidebar-foreground: oklch(0.95 0.01 60.00); --sidebar-primary: oklch(0.40 0.06 34.00); --sidebar-primary-foreground: oklch(1.00 0 0); --sidebar-accent: oklch(0.60 0.07 56.00); --sidebar-accent-foreground: oklch(0.15 0.01 350.00); --sidebar-border: oklch(0.25 0.01 340.00); --sidebar-ring: oklch(0.45 0.10 35.00); --font-sans: Montserrat, sans-serif; --font-serif: Merriweather, serif; --font-mono: Ubuntu Mono, monospace; --radius: 0.625rem; --shadow-2xs: 0px 6px 12px -3px hsl(0 0% 0% / 0.04); --shadow-xs: 0px 6px 12px -3px hsl(0 0% 0% / 0.04); --shadow-sm: 0px 6px 12px -3px hsl(0 0% 0% / 0.09), 0px 1px 2px -4px hsl(0 0% 0% / 0.09); --shadow: 0px 6px 12px -3px hsl(0 0% 0% / 0.09), 0px 1px 2px -4px hsl(0 0% 0% / 0.09); --shadow-md: 0px 6px 12px -3px hsl(0 0% 0% / 0.09), 0px 2px 4px -4px hsl(0 0% 0% / 0.09); --shadow-lg: 0px 6px 12px -3px hsl(0 0% 0% / 0.09), 0px 4px 6px -4px hsl(0 0% 0% / 0.09); --shadow-xl: 0px 6px 12px -3px hsl(0 0% 0% / 0.09), 0px 8px 10px -4px hsl(0 0% 0% / 0.09); --shadow-2xl: 0px 6px 12px -3px hsl(0 0% 0% / 0.22); } @theme inline { --color-background: var(--background); --color-foreground: var(--foreground); --color-card: var(--card); --color-card-foreground: var(--card-foreground); --color-popover: var(--popover); --color-popover-foreground: var(--popover-foreground); --color-primary: var(--primary); --color-primary-foreground: var(--primary-foreground); --color-secondary: var(--secondary); --color-secondary-foreground: var(--secondary-foreground); --color-muted: var(--muted); --color-muted-foreground: var(--muted-foreground); --color-accent: var(--accent); --color-accent-foreground: var(--accent-foreground); --color-destructive: var(--destructive); --color-destructive-foreground: var(--destructive-foreground); --color-border: var(--border); --color-input: var(--input); --color-ring: var(--ring); --color-chart-1: var(--chart-1); --color-chart-2: var(--chart-2); --color-chart-3: var(--chart-3); --color-chart-4: var(--chart-4); --color-chart-5: var(--chart-5); --color-sidebar: var(--sidebar); --color-sidebar-foreground: var(--sidebar-foreground); --color-sidebar-primary: var(--sidebar-primary); --color-sidebar-primary-foreground: var(--sidebar-primary-foreground); --color-sidebar-accent: var(--sidebar-accent); --color-sidebar-accent-foreground: var(--sidebar-accent-foreground); --color-sidebar-border: var(--sidebar-border); --color-sidebar-ring: var(--sidebar-ring); --font-sans: var(--font-sans); --font-mono: var(--font-mono); --font-serif: var(--font-serif); --radius-sm: calc(var(--radius) - 4px); --radius-md: calc(var(--radius) - 2px); --radius-lg: var(--radius); --radius-xl: calc(var(--radius) + 4px); --shadow-2xs: var(--shadow-2xs); --shadow-xs: var(--shadow-xs); --shadow-sm: var(--shadow-sm); --shadow: var(--shadow); --shadow-md: var(--shadow-md); --shadow-lg: var(--shadow-lg); --shadow-xl: var(--shadow-xl); --shadow-2xl: var(--shadow-2xl); } @layer base { * { @apply border-border outline-ring/50; } body { @apply bg-background text-foreground; letter-spacing: var(--tracking-normal); } } @layer utilities { /* Hide scrollbar for Chrome, Safari and Opera */ .no-scrollbar::-webkit-scrollbar { display: none; } /* Hide scrollbar for IE, Edge and Firefox */ .no-scrollbar { -ms-overflow-style: none; /* IE and Edge */ /* Use Firefox-specific scrollbar hiding when supported */ scrollbar-width: none; } } ``` ## /app/layout.tsx ```tsx path="/app/layout.tsx" import type { Metadata } from "next"; import { Inter } from "next/font/google"; import { ChatSidebar } from "@/components/chat-sidebar"; import { SidebarTrigger } from "@/components/ui/sidebar"; import { Menu } from "lucide-react"; import { Providers } from "./providers"; import "./globals.css"; import Script from "next/script"; const inter = Inter({ subsets: ["latin"] }); export const metadata: Metadata = { metadataBase: new URL("https://mcp.scira.ai"), title: "Scira MCP Chat", description: "Scira MCP Chat is a minimalistic MCP client with a good feature set.", openGraph: { siteName: "Scira MCP Chat", url: "https://mcp.scira.ai", images: [ { url: "https://mcp.scira.ai/opengraph-image.png", width: 1200, height: 630, }, ], }, twitter: { card: "summary_large_image", title: "Scira MCP Chat", description: "Scira MCP Chat is a minimalistic MCP client with a good feature set.", images: ["https://mcp.scira.ai/twitter-image.png"], }, }; export default function RootLayout({ children, }: Readonly<{ children: React.ReactNode; }>) { return (
{children}