Skip to main content
Glama
advanced.ts•32.7 kB
import { z } from "zod"; /** * Advanced Tools - Sophisticated generators using Code-MCP's own analysis */ // ============================================ // TypeScript Helper Tool // ============================================ export const typescriptHelperSchema = { name: "typescript_helper", description: "Generates TypeScript types, interfaces, utility types, and common patterns", inputSchema: z.object({ pattern: z.enum([ "interface", "type", "enum", "generic", "utility-types", "discriminated-union", "mapped-type", "conditional-type", "api-response", "form-data", "state-machine" ]).describe("TypeScript pattern to generate"), name: z.string().describe("Name for the type/interface"), fields: z.array(z.object({ name: z.string(), type: z.string(), optional: z.boolean().optional() })).optional().describe("Fields for the type") }) }; export function typescriptHelperHandler(args: { pattern: string; name: string; fields?: Array<{ name: string; type: string; optional?: boolean }> }) { const { pattern, name, fields = [] } = args; const patterns: Record<string, () => string> = { "interface": () => { const fieldStrs = fields.map(f => ` ${f.name}${f.optional ? '?' : ''}: ${f.type};` ).join('\n'); return `interface ${name} { ${fieldStrs || ' // Add your fields here'} } // Usage const example: ${name} = { // Fill in required fields };`; }, "type": () => { const fieldStrs = fields.map(f => ` ${f.name}${f.optional ? '?' : ''}: ${f.type};` ).join('\n'); return `type ${name} = { ${fieldStrs || ' // Add your fields here'} }; // Type alias examples type ${name}Partial = Partial<${name}>; type ${name}Required = Required<${name}>; type ${name}Keys = keyof ${name};`; }, "enum": () => `enum ${name} { Active = 'active', Inactive = 'inactive', Pending = 'pending', } // Const enum (inlined at compile time) const enum ${name}Const { Active = 'active', Inactive = 'inactive', } // Object alternative (better tree-shaking) const ${name}Values = { Active: 'active', Inactive: 'inactive', Pending: 'pending', } as const; type ${name}Value = typeof ${name}Values[keyof typeof ${name}Values];`, "generic": () => `// Generic function function get${name}<T>(items: T[], predicate: (item: T) => boolean): T | undefined { return items.find(predicate); } // Generic interface interface ${name}Container<T> { data: T; metadata: { createdAt: Date; updatedAt: Date; }; } // Generic class class ${name}Repository<T extends { id: string }> { private items: Map<string, T> = new Map(); add(item: T): void { this.items.set(item.id, item); } get(id: string): T | undefined { return this.items.get(id); } getAll(): T[] { return Array.from(this.items.values()); } } // Constrained generic function merge${name}<T extends object, U extends object>(a: T, b: U): T & U { return { ...a, ...b }; }`, "utility-types": () => `// Pick specific fields type ${name}Preview = Pick<${name}, 'id' | 'name'>; // Omit specific fields type ${name}Create = Omit<${name}, 'id' | 'createdAt'>; // Make all optional type ${name}Update = Partial<${name}>; // Make all required type ${name}Complete = Required<${name}>; // Make readonly type ${name}Frozen = Readonly<${name}>; // Record type type ${name}Map = Record<string, ${name}>; // Extract from union type ${name}Status = Extract<Status, 'active' | 'pending'>; // Exclude from union type ${name}InactiveStatus = Exclude<Status, 'active'>; // Non-nullable type ${name}Defined = NonNullable<${name} | null | undefined>; // Return type of function type ${name}Result = ReturnType<typeof get${name}>; // Parameters of function type ${name}Params = Parameters<typeof create${name}>;`, "discriminated-union": () => `// Discriminated union for ${name} type ${name}Success = { status: 'success'; data: unknown; }; type ${name}Error = { status: 'error'; error: string; code: number; }; type ${name}Loading = { status: 'loading'; }; type ${name}Result = ${name}Success | ${name}Error | ${name}Loading; // Type-safe handler function handle${name}(result: ${name}Result) { switch (result.status) { case 'success': console.log(result.data); // TypeScript knows data exists break; case 'error': console.error(result.error, result.code); // TypeScript knows error/code exist break; case 'loading': console.log('Loading...'); break; } }`, "mapped-type": () => `// Mapped type: transform all properties type ${name}Nullable<T> = { [K in keyof T]: T[K] | null; }; // Mapped type with modifier type ${name}Mutable<T> = { -readonly [K in keyof T]: T[K]; }; // Conditional mapped type type ${name}Optional<T> = { [K in keyof T as T[K] extends Function ? never : K]?: T[K]; }; // Key remapping type ${name}Getters<T> = { [K in keyof T as \`get\${Capitalize<string & K>}\`]: () => T[K]; }; // Example usage interface Original { id: string; name: string; readonly locked: boolean; } type ${name}Example = ${name}Nullable<Original>; // Result: { id: string | null; name: string | null; locked: boolean | null; }`, "conditional-type": () => `// Basic conditional type type ${name}Check<T> = T extends string ? 'string' : 'other'; // Infer keyword type ${name}Unwrap<T> = T extends Promise<infer U> ? U : T; type ${name}ArrayElement<T> = T extends (infer U)[] ? U : never; // Distributive conditional type ${name}NonNullable<T> = T extends null | undefined ? never : T; // Complex conditional type ${name}DeepReadonly<T> = T extends object ? { readonly [K in keyof T]: ${name}DeepReadonly<T[K]> } : T; // Function return type extraction type ${name}ReturnType<T> = T extends (...args: any[]) => infer R ? R : never; // Tuple to union type ${name}TupleToUnion<T extends readonly unknown[]> = T[number]; // Example type Result = ${name}Unwrap<Promise<string>>; // string type Element = ${name}ArrayElement<number[]>; // number`, "api-response": () => `// API Response wrapper interface ${name}Response<T> { success: boolean; data?: T; error?: { code: string; message: string; details?: Record<string, unknown>; }; meta?: { page?: number; limit?: number; total?: number; hasMore?: boolean; }; } // Paginated response interface ${name}PaginatedResponse<T> extends ${name}Response<T[]> { meta: { page: number; limit: number; total: number; hasMore: boolean; }; } // Type guards function is${name}Success<T>(response: ${name}Response<T>): response is ${name}Response<T> & { success: true; data: T } { return response.success === true && response.data !== undefined; } function is${name}Error<T>(response: ${name}Response<T>): response is ${name}Response<T> & { success: false; error: NonNullable<${name}Response<T>['error']> } { return response.success === false && response.error !== undefined; } // Usage async function fetch${name}(): Promise<${name}Response<User>> { // Implementation return { success: true, data: { id: '1', name: 'John' } }; }`, "form-data": () => `// Form data type with validation interface ${name}FormData { // Text fields name: string; email: string; // Optional fields phone?: string; bio?: string; // Select/Radio role: 'user' | 'admin' | 'moderator'; // Checkbox agreeToTerms: boolean; // Multi-select interests: string[]; // File upload avatar?: File; } // Form errors type type ${name}FormErrors = { [K in keyof ${name}FormData]?: string; }; // Form touched state type ${name}FormTouched = { [K in keyof ${name}FormData]?: boolean; }; // Form state interface ${name}FormState { values: ${name}FormData; errors: ${name}FormErrors; touched: ${name}FormTouched; isSubmitting: boolean; isValid: boolean; } // Initial values const ${name.toLowerCase()}InitialValues: ${name}FormData = { name: '', email: '', role: 'user', agreeToTerms: false, interests: [], };`, "state-machine": () => `// State machine for ${name} type ${name}State = 'idle' | 'loading' | 'success' | 'error'; type ${name}Event = | { type: 'FETCH' } | { type: 'SUCCESS'; data: unknown } | { type: 'ERROR'; error: string } | { type: 'RESET' }; interface ${name}Context { data: unknown | null; error: string | null; attempts: number; } // State machine definition const ${name.toLowerCase()}Machine = { initial: 'idle' as ${name}State, context: { data: null, error: null, attempts: 0, } as ${name}Context, states: { idle: { on: { FETCH: 'loading' }, }, loading: { on: { SUCCESS: 'success', ERROR: 'error', }, }, success: { on: { RESET: 'idle' }, }, error: { on: { FETCH: 'loading', RESET: 'idle', }, }, }, }; // Transition function function ${name.toLowerCase()}Transition( state: ${name}State, event: ${name}Event ): ${name}State { const stateConfig = ${name.toLowerCase()}Machine.states[state]; const nextState = stateConfig.on[event.type as keyof typeof stateConfig.on]; return (nextState as ${name}State) || state; }`, }; const generator = patterns[pattern]; if (!generator) { return { content: [{ type: "text", text: `Unknown pattern: ${pattern}` }] }; } return { content: [{ type: "text", text: `# TypeScript: ${pattern} for "${name}"\n\n\`\`\`typescript\n${generator()}\n\`\`\`\n\nāœ… Copy and customize for your project.` }] }; } // ============================================ // API Client Generator // ============================================ export const apiClientSchema = { name: "generate_api_client", description: "Generates type-safe API client code with fetch or axios", inputSchema: z.object({ baseUrl: z.string().describe("Base URL for the API"), endpoints: z.array(z.object({ name: z.string(), method: z.enum(["GET", "POST", "PUT", "PATCH", "DELETE"]), path: z.string() })).describe("API endpoints to generate"), library: z.enum(["fetch", "axios"]).optional().default("fetch") }) }; export function apiClientHandler(args: { baseUrl: string; endpoints: Array<{ name: string; method: string; path: string }>; library?: string }) { const { baseUrl, endpoints, library = "fetch" } = args; const fetchClient = `// API Client - Generated by Code-MCP const BASE_URL = '${baseUrl}'; interface ApiResponse<T> { data: T; error?: string; } interface RequestOptions { headers?: Record<string, string>; signal?: AbortSignal; } class ApiClient { private token: string | null = null; setToken(token: string) { this.token = token; } private async request<T>( method: string, path: string, body?: unknown, options?: RequestOptions ): Promise<ApiResponse<T>> { const headers: Record<string, string> = { 'Content-Type': 'application/json', ...options?.headers, }; if (this.token) { headers['Authorization'] = \`Bearer \${this.token}\`; } try { const response = await fetch(\`\${BASE_URL}\${path}\`, { method, headers, body: body ? JSON.stringify(body) : undefined, signal: options?.signal, }); if (!response.ok) { const error = await response.json().catch(() => ({ message: 'Request failed' })); return { data: null as T, error: error.message || \`HTTP \${response.status}\` }; } const data = await response.json(); return { data }; } catch (error) { return { data: null as T, error: error instanceof Error ? error.message : 'Unknown error' }; } } ${endpoints.map(ep => { const hasBody = ['POST', 'PUT', 'PATCH'].includes(ep.method); const params = hasBody ? 'data: unknown, options?: RequestOptions' : 'options?: RequestOptions'; const bodyArg = hasBody ? ', data' : ''; return ` async ${ep.name}(${params}) { return this.request('${ep.method}', '${ep.path}'${bodyArg}, options); }`; }).join('\n\n')} } export const api = new ApiClient(); // Usage examples: // api.setToken('your-jwt-token'); // const result = await api.${endpoints[0]?.name || 'getData'}();`; const axiosClient = `// API Client - Generated by Code-MCP import axios, { AxiosInstance, AxiosError, InternalAxiosRequestConfig } from 'axios'; const BASE_URL = '${baseUrl}'; interface ApiResponse<T> { data: T; error?: string; } class ApiClient { private client: AxiosInstance; constructor() { this.client = axios.create({ baseURL: BASE_URL, timeout: 10000, headers: { 'Content-Type': 'application/json', }, }); // Request interceptor for auth this.client.interceptors.request.use((config: InternalAxiosRequestConfig) => { const token = localStorage.getItem('token'); if (token && config.headers) { config.headers.Authorization = \`Bearer \${token}\`; } return config; }); // Response interceptor for error handling this.client.interceptors.response.use( (response) => response, (error: AxiosError) => { if (error.response?.status === 401) { // Handle unauthorized localStorage.removeItem('token'); window.location.href = '/login'; } return Promise.reject(error); } ); } private async request<T>( method: string, path: string, data?: unknown ): Promise<ApiResponse<T>> { try { const response = await this.client.request<T>({ method, url: path, data }); return { data: response.data }; } catch (error) { const message = error instanceof AxiosError ? error.response?.data?.message || error.message : 'Unknown error'; return { data: null as T, error: message }; } } ${endpoints.map(ep => { const hasBody = ['POST', 'PUT', 'PATCH'].includes(ep.method); const params = hasBody ? 'data: unknown' : ''; const dataArg = hasBody ? ', data' : ''; return ` async ${ep.name}(${params}) { return this.request('${ep.method}', '${ep.path}'${dataArg}); }`; }).join('\n\n')} } export const api = new ApiClient();`; const client = library === "axios" ? axiosClient : fetchClient; return { content: [{ type: "text", text: `# API Client (${library})\n\n\`\`\`typescript\n${client}\n\`\`\`\n\n## Generated Endpoints\n${endpoints.map(e => `- \`${e.method} ${e.path}\` → \`api.${e.name}()\``).join('\n')}` }] }; } // ============================================ // SQL Helper Tool // ============================================ export const sqlHelperSchema = { name: "sql_helper", description: "Generates SQL queries, migrations, and database operations", inputSchema: z.object({ operation: z.enum([ "create-table", "alter-table", "index", "migration", "select", "insert", "update", "delete", "join", "aggregate", "cte", "window-function" ]).describe("SQL operation to generate"), table: z.string().describe("Table name"), columns: z.array(z.object({ name: z.string(), type: z.string(), constraints: z.string().optional() })).optional(), database: z.enum(["postgres", "mysql", "sqlite"]).optional().default("postgres") }) }; export function sqlHelperHandler(args: { operation: string; table: string; columns?: Array<{ name: string; type: string; constraints?: string }>; database?: string }) { const { operation, table, columns = [], database = "postgres" } = args; const sqlGenerators: Record<string, () => string> = { "create-table": () => { const cols = columns.length ? columns.map(c => ` ${c.name} ${c.type}${c.constraints ? ' ' + c.constraints : ''}` ).join(',\n') : ` id UUID PRIMARY KEY DEFAULT gen_random_uuid(), name VARCHAR(255) NOT NULL, email VARCHAR(255) UNIQUE NOT NULL, status VARCHAR(50) DEFAULT 'active', metadata JSONB, created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(), updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()`; return `-- Create ${table} table CREATE TABLE IF NOT EXISTS ${table} ( ${cols} ); -- Add updated_at trigger CREATE OR REPLACE FUNCTION update_updated_at() RETURNS TRIGGER AS $$ BEGIN NEW.updated_at = NOW(); RETURN NEW; END; $$ LANGUAGE plpgsql; CREATE TRIGGER ${table}_updated_at BEFORE UPDATE ON ${table} FOR EACH ROW EXECUTE FUNCTION update_updated_at();`; }, "alter-table": () => `-- Add column ALTER TABLE ${table} ADD COLUMN new_column VARCHAR(255); -- Drop column ALTER TABLE ${table} DROP COLUMN old_column; -- Rename column ALTER TABLE ${table} RENAME COLUMN old_name TO new_name; -- Change column type ALTER TABLE ${table} ALTER COLUMN column_name TYPE TEXT; -- Add constraint ALTER TABLE ${table} ADD CONSTRAINT ${table}_unique_email UNIQUE (email); -- Add foreign key ALTER TABLE ${table} ADD CONSTRAINT ${table}_user_fk FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE; -- Drop constraint ALTER TABLE ${table} DROP CONSTRAINT constraint_name;`, "index": () => `-- Basic index CREATE INDEX idx_${table}_name ON ${table}(name); -- Unique index CREATE UNIQUE INDEX idx_${table}_email ON ${table}(email); -- Composite index CREATE INDEX idx_${table}_status_created ON ${table}(status, created_at DESC); -- Partial index (only active records) CREATE INDEX idx_${table}_active ON ${table}(name) WHERE status = 'active'; -- GIN index for JSONB CREATE INDEX idx_${table}_metadata ON ${table} USING GIN(metadata); -- Full-text search index CREATE INDEX idx_${table}_search ON ${table} USING GIN(to_tsvector('english', name || ' ' || description)); -- Drop index DROP INDEX IF EXISTS idx_${table}_name;`, "migration": () => `-- Migration: create_${table}_table -- Created: ${new Date().toISOString()} -- Up Migration BEGIN; CREATE TABLE IF NOT EXISTS ${table} ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), name VARCHAR(255) NOT NULL, created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(), updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW() ); CREATE INDEX idx_${table}_name ON ${table}(name); COMMIT; -- Down Migration BEGIN; DROP TABLE IF EXISTS ${table}; COMMIT;`, "select": () => `-- Basic select SELECT * FROM ${table} WHERE id = $1; -- Select with columns SELECT id, name, email, created_at FROM ${table}; -- Select with conditions SELECT * FROM ${table} WHERE status = 'active' AND created_at > NOW() - INTERVAL '30 days'; -- Select with ordering and pagination SELECT * FROM ${table} ORDER BY created_at DESC LIMIT $1 OFFSET $2; -- Select with search SELECT * FROM ${table} WHERE name ILIKE '%' || $1 || '%' OR email ILIKE '%' || $1 || '%'; -- Select exists SELECT EXISTS(SELECT 1 FROM ${table} WHERE email = $1);`, "insert": () => `-- Single insert INSERT INTO ${table} (name, email, status) VALUES ($1, $2, $3) RETURNING *; -- Insert with defaults INSERT INTO ${table} (name, email) VALUES ($1, $2) RETURNING id; -- Bulk insert INSERT INTO ${table} (name, email, status) VALUES ('John', 'john@example.com', 'active'), ('Jane', 'jane@example.com', 'active') RETURNING *; -- Insert on conflict (upsert) INSERT INTO ${table} (id, name, email) VALUES ($1, $2, $3) ON CONFLICT (email) DO UPDATE SET name = EXCLUDED.name, updated_at = NOW() RETURNING *;`, "join": () => `-- Inner join SELECT ${table}.*, users.name AS user_name FROM ${table} INNER JOIN users ON ${table}.user_id = users.id; -- Left join SELECT ${table}.*, COUNT(comments.id) AS comment_count FROM ${table} LEFT JOIN comments ON ${table}.id = comments.${table}_id GROUP BY ${table}.id; -- Multiple joins SELECT ${table}.*, u.name AS author_name, c.name AS category_name FROM ${table} JOIN users u ON ${table}.author_id = u.id LEFT JOIN categories c ON ${table}.category_id = c.id WHERE ${table}.status = 'published';`, "aggregate": () => `-- Count SELECT COUNT(*) FROM ${table} WHERE status = 'active'; -- Count with group SELECT status, COUNT(*) as count FROM ${table} GROUP BY status; -- Sum/Avg SELECT SUM(amount) AS total, AVG(amount) AS average, MIN(amount) AS minimum, MAX(amount) AS maximum FROM ${table}; -- Count distinct SELECT COUNT(DISTINCT user_id) AS unique_users FROM ${table}; -- Having clause SELECT user_id, COUNT(*) as order_count FROM ${table} GROUP BY user_id HAVING COUNT(*) > 5;`, "cte": () => `-- Common Table Expression (WITH clause) WITH active_${table} AS ( SELECT * FROM ${table} WHERE status = 'active' ), recent_${table} AS ( SELECT * FROM active_${table} WHERE created_at > NOW() - INTERVAL '7 days' ) SELECT * FROM recent_${table} ORDER BY created_at DESC; -- Recursive CTE (for hierarchical data) WITH RECURSIVE ${table}_tree AS ( -- Base case SELECT id, parent_id, name, 1 AS depth FROM ${table} WHERE parent_id IS NULL UNION ALL -- Recursive case SELECT t.id, t.parent_id, t.name, tt.depth + 1 FROM ${table} t JOIN ${table}_tree tt ON t.parent_id = tt.id WHERE tt.depth < 10 -- Prevent infinite recursion ) SELECT * FROM ${table}_tree;`, "window-function": () => `-- Row number SELECT *, ROW_NUMBER() OVER (ORDER BY created_at DESC) AS row_num FROM ${table}; -- Rank within groups SELECT *, RANK() OVER (PARTITION BY category_id ORDER BY views DESC) AS category_rank FROM ${table}; -- Running total SELECT *, SUM(amount) OVER (ORDER BY created_at) AS running_total FROM ${table}; -- Moving average SELECT *, AVG(amount) OVER ( ORDER BY created_at ROWS BETWEEN 6 PRECEDING AND CURRENT ROW ) AS moving_avg_7 FROM ${table}; -- Lead/Lag SELECT *, LAG(amount, 1) OVER (ORDER BY created_at) AS prev_amount, LEAD(amount, 1) OVER (ORDER BY created_at) AS next_amount FROM ${table};`, }; const generator = sqlGenerators[operation]; if (!generator) { return { content: [{ type: "text", text: `Unknown operation: ${operation}` }] }; } return { content: [{ type: "text", text: `# SQL: ${operation} for "${table}" (${database})\n\n\`\`\`sql\n${generator()}\n\`\`\`\n\nšŸ’” Adjust syntax for ${database} if needed.` }] }; } // ============================================ // README Generator // ============================================ export const readmeGeneratorSchema = { name: "generate_readme", description: "Generates a complete README.md file for any project", inputSchema: z.object({ projectName: z.string().describe("Name of the project"), description: z.string().describe("Short project description"), type: z.enum(["library", "cli", "api", "webapp", "fullstack"]).describe("Project type"), language: z.string().describe("Primary programming language"), features: z.array(z.string()).optional().describe("Key features list") }) }; export function readmeGeneratorHandler(args: { projectName: string; description: string; type: string; language: string; features?: string[] }) { const { projectName, description, type, language, features = [] } = args; const featureList = features.length ? features.map(f => `- ${f}`).join('\n') : `- Feature 1\n- Feature 2\n- Feature 3`; const installSection: Record<string, string> = { library: `\`\`\`bash npm install ${projectName.toLowerCase()} # or yarn add ${projectName.toLowerCase()} # or pnpm add ${projectName.toLowerCase()} \`\`\``, cli: `\`\`\`bash npm install -g ${projectName.toLowerCase()} # or npx ${projectName.toLowerCase()} \`\`\``, api: `\`\`\`bash git clone https://github.com/username/${projectName.toLowerCase()}.git cd ${projectName.toLowerCase()} npm install cp .env.example .env npm run dev \`\`\``, webapp: `\`\`\`bash git clone https://github.com/username/${projectName.toLowerCase()}.git cd ${projectName.toLowerCase()} npm install npm run dev \`\`\``, fullstack: `\`\`\`bash git clone https://github.com/username/${projectName.toLowerCase()}.git cd ${projectName.toLowerCase()} npm install cp .env.example .env docker-compose up -d # Start databases npm run dev \`\`\``, }; const usageSection: Record<string, string> = { library: `\`\`\`${language.toLowerCase()} import { something } from '${projectName.toLowerCase()}'; // Use the library const result = something(); console.log(result); \`\`\``, cli: `\`\`\`bash # Basic usage ${projectName.toLowerCase()} --help # Run a command ${projectName.toLowerCase()} init my-project # With options ${projectName.toLowerCase()} build --output ./dist \`\`\``, api: `\`\`\`bash # Health check curl http://localhost:3000/health # Get all items curl http://localhost:3000/api/items # Create item curl -X POST http://localhost:3000/api/items \\ -H "Content-Type: application/json" \\ -d '{"name": "example"}' \`\`\``, webapp: `Visit \`http://localhost:3000\` after starting the development server.`, fullstack: `1. Start the backend: \`npm run dev:api\` 2. Start the frontend: \`npm run dev:web\` 3. Visit \`http://localhost:3000\``, }; const readme = `# ${projectName} ${description} [![License](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE) [![Build Status](https://img.shields.io/github/actions/workflow/status/username/${projectName.toLowerCase()}/ci.yml)](https://github.com/username/${projectName.toLowerCase()}/actions) ## ✨ Features ${featureList} ## šŸ“¦ Installation ${installSection[type]} ## šŸš€ Quick Start ${usageSection[type]} ## šŸ“– Documentation For detailed documentation, see [docs/](./docs/) or visit our [documentation site](#). ## šŸ› ļø Development \`\`\`bash # Install dependencies npm install # Run in development mode npm run dev # Run tests npm test # Build for production npm run build # Lint code npm run lint \`\`\` ## šŸ—‚ļø Project Structure \`\`\` ${projectName.toLowerCase()}/ ā”œā”€ā”€ src/ # Source code ā”œā”€ā”€ tests/ # Test files ā”œā”€ā”€ docs/ # Documentation ā”œā”€ā”€ scripts/ # Build/deploy scripts ā”œā”€ā”€ .github/ # GitHub Actions & templates ā”œā”€ā”€ package.json ā”œā”€ā”€ tsconfig.json └── README.md \`\`\` ## šŸ¤ Contributing Contributions are welcome! Please read our [Contributing Guide](CONTRIBUTING.md) for details. 1. Fork the repository 2. Create your feature branch (\`git checkout -b feature/amazing\`) 3. Commit your changes (\`git commit -m 'Add amazing feature'\`) 4. Push to the branch (\`git push origin feature/amazing\`) 5. Open a Pull Request ## šŸ“„ License This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details. ## šŸ™ Acknowledgments - Thanks to all contributors - Inspired by [project/tool](#) --- Made with ā¤ļø by [Your Name](https://github.com/username)`; return { content: [{ type: "text", text: `# Generated README for ${projectName}\n\n\`\`\`markdown\n${readme}\n\`\`\`` }] }; } // ============================================ // License Generator // ============================================ export const licenseGeneratorSchema = { name: "generate_license", description: "Generates license files for open source projects", inputSchema: z.object({ license: z.enum(["MIT", "Apache-2.0", "GPL-3.0", "BSD-3-Clause", "ISC", "Unlicense"]).describe("License type"), author: z.string().describe("Author/Organization name"), year: z.number().optional() }) }; export function licenseGeneratorHandler(args: { license: string; author: string; year?: number }) { const { license, author, year = new Date().getFullYear() } = args; const licenses: Record<string, string> = { "MIT": `MIT License Copyright (c) ${year} ${author} Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.`, "Apache-2.0": ` Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ Copyright ${year} ${author} 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.`, "ISC": `ISC License Copyright (c) ${year} ${author} Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.`, "Unlicense": `This is free and unencumbered software released into the public domain. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means. In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. For more information, please refer to <http://unlicense.org/>`, }; const licenseText = licenses[license] || licenses["MIT"]; return { content: [{ type: "text", text: `# ${license} License\n\nSave as \`LICENSE\` in your project root:\n\n\`\`\`\n${licenseText}\n\`\`\`` }] }; } // Export all export const advancedTools = { typescriptHelperSchema, typescriptHelperHandler, apiClientSchema, apiClientHandler, sqlHelperSchema, sqlHelperHandler, readmeGeneratorSchema, readmeGeneratorHandler, licenseGeneratorSchema, licenseGeneratorHandler, };

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/millsydotdev/Code-MCP'

If you have feedback or need assistance with the MCP directory API, please join our Discord server