summaryrefslogtreecommitdiff
path: root/mcp-servers/simple-mcp-server/.claude/commands/add-resource.md
blob: aff9e54d50b37c95781d914333aa49edd1f6b22c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
# Add Resource to MCP Server

Adds a new resource endpoint to your MCP server with proper URI handling.

## Usage

```
/add-resource <name> <description> [uri-pattern] [mime-type]
```

## Examples

```
/add-resource config "Server configuration" config://settings application/json
/add-resource users "User database" data://users/{id} application/json
/add-resource files "File system access" file:///{path} text/plain
```

## Implementation

```typescript
import * as fs from 'fs/promises';
import * as path from 'path';

async function addResource(
  name: string,
  description: string,
  uriPattern?: string,
  mimeType: string = 'application/json'
) {
  // Generate URI pattern if not provided
  const uri = uriPattern || `${name}://default`;
  
  // Generate resource file
  const resourceContent = generateResourceFile(name, description, uri, mimeType);
  
  // Write resource file
  const resourcePath = path.join('src/resources', `${name}.ts`);
  await fs.writeFile(resourcePath, resourceContent);
  
  // Update resource index
  await updateResourceIndex(name);
  
  // Generate test file
  const testContent = generateResourceTest(name, uri);
  const testPath = path.join('tests/unit/resources', `${name}.test.ts`);
  await fs.writeFile(testPath, testContent);
  
  console.log(`✅ Resource "${name}" added successfully!`);
  console.log(`  - Implementation: ${resourcePath}`);
  console.log(`  - Test file: ${testPath}`);
  console.log(`  - URI pattern: ${uri}`);
  console.log(`  - MIME type: ${mimeType}`);
  console.log(`\nNext steps:`);
  console.log(`  1. Implement the resource provider in ${resourcePath}`);
  console.log(`  2. Test with MCP Inspector`);
}

function generateResourceFile(
  name: string,
  description: string,
  uri: string,
  mimeType: string
): string {
  const hasDynamicParams = uri.includes('{');
  
  return `
import type { Resource, ResourceContent } from '../types/resources.js';

export const ${name}Resource: Resource = {
  uri: '${uri}',
  name: '${name}',
  description: '${description}',
  mimeType: '${mimeType}',
};

export async function read${capitalize(name)}Resource(
  uri: string
): Promise<ResourceContent[]> {
  ${hasDynamicParams ? generateDynamicResourceHandler(uri) : generateStaticResourceHandler()}
  
  return [
    {
      uri,
      mimeType: '${mimeType}',
      text: ${mimeType === 'application/json' ? 'JSON.stringify(data, null, 2)' : 'data'},
    },
  ];
}

${generateResourceDataFunction(name, mimeType)}
`;
}

function generateDynamicResourceHandler(uriPattern: string): string {
  return `
  // Parse dynamic parameters from URI
  const params = parseUriParams('${uriPattern}', uri);
  
  // Fetch data based on parameters
  const data = await fetch${capitalize(name)}Data(params);
  
  if (!data) {
    throw new Error(\`Resource not found: \${uri}\`);
  }
`;
}

function generateStaticResourceHandler(): string {
  return `
  // Fetch static resource data
  const data = await fetch${capitalize(name)}Data();
`;
}

function generateResourceDataFunction(name: string, mimeType: string): string {
  if (mimeType === 'application/json') {
    return `
async function fetch${capitalize(name)}Data(params?: Record<string, string>) {
  // TODO: Implement data fetching logic
  // This is a placeholder implementation
  
  if (params?.id) {
    // Return specific item
    return {
      id: params.id,
      name: 'Example Item',
      timestamp: new Date().toISOString(),
    };
  }
  
  // Return collection
  return {
    items: [
      { id: '1', name: 'Item 1' },
      { id: '2', name: 'Item 2' },
    ],
    total: 2,
  };
}

function parseUriParams(pattern: string, uri: string): Record<string, string> {
  // Convert pattern to regex
  const regexPattern = pattern
    .replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
    .replace(/\{(\w+)\}/g, '(?<$1>[^/]+)');
  
  const regex = new RegExp(\`^\${regexPattern}$\`);
  const match = uri.match(regex);
  
  return match?.groups || {};
}
`;
  } else {
    return `
async function fetch${capitalize(name)}Data(params?: Record<string, string>) {
  // TODO: Implement data fetching logic
  // This is a placeholder implementation
  
  return 'Resource content as ${mimeType}';
}
`;
  }
}

function capitalize(str: string): string {
  return str.charAt(0).toUpperCase() + str.slice(1);
}

function generateResourceTest(name: string, uri: string): string {
  return `
import { describe, it, expect } from 'vitest';
import { ${name}Resource, read${capitalize(name)}Resource } from '../../src/resources/${name}.js';

describe('${name} resource', () => {
  it('should have correct metadata', () => {
    expect(${name}Resource.name).toBe('${name}');
    expect(${name}Resource.uri).toBe('${uri}');
    expect(${name}Resource.description).toBeDefined();
    expect(${name}Resource.mimeType).toBeDefined();
  });
  
  it('should read resource content', async () => {
    const content = await read${capitalize(name)}Resource('${uri.replace('{id}', 'test-id')}');
    
    expect(content).toBeInstanceOf(Array);
    expect(content[0]).toHaveProperty('uri');
    expect(content[0]).toHaveProperty('mimeType');
    expect(content[0]).toHaveProperty('text');
  });
  
  it('should handle missing resources', async () => {
    // TODO: Add tests for missing resources
  });
  
  it('should validate URI format', () => {
    // TODO: Add URI validation tests
  });
});
`;
}

async function updateResourceIndex(name: string) {
  const indexPath = 'src/resources/index.ts';
  
  try {
    let content = await fs.readFile(indexPath, 'utf-8');
    
    // Add import
    const importLine = `import { ${name}Resource, read${capitalize(name)}Resource } from './${name}.js';`;
    if (!content.includes(importLine)) {
      const lastImport = content.lastIndexOf('import');
      const endOfLastImport = content.indexOf('\n', lastImport);
      content = content.slice(0, endOfLastImport + 1) + importLine + '\n' + content.slice(endOfLastImport + 1);
    }
    
    // Add to exports
    const exportPattern = /export const resources = \[([^\]]*)]\;/;
    const match = content.match(exportPattern);
    if (match) {
      const currentExports = match[1].trim();
      const newExports = currentExports ? `${currentExports},\n  ${name}Resource` : `\n  ${name}Resource\n`;
      content = content.replace(exportPattern, `export const resources = [${newExports}];`);
    }
    
    await fs.writeFile(indexPath, content);
  } catch (error) {
    // Create index file if it doesn't exist
    const newIndex = `
import { ${name}Resource, read${capitalize(name)}Resource } from './${name}.js';

export const resources = [
  ${name}Resource,
];

export const resourceReaders = {
  '${name}': read${capitalize(name)}Resource,
};
`;
    await fs.writeFile(indexPath, newIndex);
  }
}
```