index.ts 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968
  1. #!/usr/bin/env node
  2. import { Server } from '@modelcontextprotocol/sdk/server/index.js';
  3. import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
  4. import {
  5. CallToolRequestSchema,
  6. ListToolsRequestSchema,
  7. McpError,
  8. ErrorCode,
  9. } from '@modelcontextprotocol/sdk/types.js';
  10. import axios from 'axios';
  11. import { v4 as uuidv4 } from 'uuid';
  12. import dotenv from 'dotenv';
  13. import { registerAuthTools } from './tools/auth.js';
  14. import { registerOrgTools } from './tools/organizations.js';
  15. import { registerAppTools } from './tools/applications.js';
  16. import { registerSystemTools } from './tools/system.js';
  17. import { registerStorageTools } from './tools/storage.js';
  18. import { logger } from './utils/logger.js';
  19. dotenv.config();
  20. const server = new Server(
  21. {
  22. name: 'saas-platform-mcp',
  23. version: '1.0.0',
  24. },
  25. {
  26. capabilities: {
  27. tools: {},
  28. },
  29. }
  30. );
  31. // Configuration
  32. const config = {
  33. apiGateway: process.env.SAAS_API_URL || 'http://localhost',
  34. authUrl: process.env.SAAS_AUTH_URL || 'http://localhost/auth',
  35. storageUrl: process.env.SAAS_STORAGE_URL || 'http://localhost/storage',
  36. };
  37. // Store authentication state
  38. let authToken: string | null = null;
  39. let currentUser: any = null;
  40. // Create authenticated axios instance
  41. const createApiClient = (requireAuth = true) => {
  42. const client = axios.create({
  43. baseURL: config.apiGateway,
  44. headers: {
  45. 'Content-Type': 'application/json',
  46. ...(requireAuth && authToken ? { Authorization: `Bearer ${authToken}` } : {}),
  47. },
  48. });
  49. // Add response interceptor for error handling
  50. client.interceptors.response.use(
  51. (response) => response,
  52. (error) => {
  53. if (error.response?.status === 401 && requireAuth) {
  54. logger.error('Authentication expired');
  55. authToken = null;
  56. currentUser = null;
  57. throw new McpError(
  58. ErrorCode.Unauthorized,
  59. 'Authentication expired. Please login again.'
  60. );
  61. }
  62. throw error;
  63. }
  64. );
  65. return client;
  66. };
  67. // Export utilities for other modules
  68. export { createApiClient, config, authToken, currentUser };
  69. // Authentication helper
  70. export const setAuth = (token: string, user: any) => {
  71. authToken = token;
  72. currentUser = user;
  73. logger.info(`Authenticated as user: ${user.email}`);
  74. };
  75. export const clearAuth = () => {
  76. authToken = null;
  77. currentUser = null;
  78. logger.info('Authentication cleared');
  79. };
  80. // Register all tool handlers
  81. registerAuthTools(server, setAuth, clearAuth);
  82. registerOrgTools(server, createApiClient);
  83. registerAppTools(server, createApiClient);
  84. registerSystemTools(server, config);
  85. registerStorageTools(server, config);
  86. // List available tools
  87. server.setRequestHandler(ListToolsRequestSchema, async () => {
  88. return {
  89. tools: [
  90. // Authentication tools
  91. {
  92. name: 'saas_login',
  93. description: 'Login to the SaaS platform',
  94. inputSchema: {
  95. type: 'object',
  96. properties: {
  97. email: { type: 'string', description: 'User email' },
  98. password: { type: 'string', description: 'User password' },
  99. },
  100. required: ['email', 'password'],
  101. },
  102. },
  103. {
  104. name: 'saas_logout',
  105. description: 'Logout from the SaaS platform',
  106. inputSchema: {
  107. type: 'object',
  108. properties: {},
  109. },
  110. },
  111. {
  112. name: 'saas_get_current_user',
  113. description: 'Get current authenticated user information',
  114. inputSchema: {
  115. type: 'object',
  116. properties: {},
  117. },
  118. },
  119. {
  120. name: 'saas_register_user',
  121. description: 'Register a new user account',
  122. inputSchema: {
  123. type: 'object',
  124. properties: {
  125. email: { type: 'string', description: 'User email' },
  126. password: { type: 'string', description: 'User password (min 6 characters)' },
  127. firstName: { type: 'string', description: 'First name' },
  128. lastName: { type: 'string', description: 'Last name' },
  129. },
  130. required: ['email', 'password'],
  131. },
  132. },
  133. // Organization tools
  134. {
  135. name: 'saas_list_organizations',
  136. description: 'List organizations for the current user',
  137. inputSchema: {
  138. type: 'object',
  139. properties: {},
  140. },
  141. },
  142. {
  143. name: 'saas_create_organization',
  144. description: 'Create a new organization',
  145. inputSchema: {
  146. type: 'object',
  147. properties: {
  148. name: { type: 'string', description: 'Organization name' },
  149. slug: { type: 'string', description: 'Organization slug (unique identifier)' },
  150. description: { type: 'string', description: 'Organization description' },
  151. },
  152. required: ['name', 'slug'],
  153. },
  154. },
  155. {
  156. name: 'saas_get_organization',
  157. description: 'Get organization details',
  158. inputSchema: {
  159. type: 'object',
  160. properties: {
  161. id: { type: 'string', description: 'Organization ID' },
  162. },
  163. required: ['id'],
  164. },
  165. },
  166. // Application tools
  167. {
  168. name: 'saas_list_applications',
  169. description: 'List applications in an organization',
  170. inputSchema: {
  171. type: 'object',
  172. properties: {
  173. organizationId: { type: 'string', description: 'Organization ID' },
  174. },
  175. required: ['organizationId'],
  176. },
  177. },
  178. {
  179. name: 'saas_create_application',
  180. description: 'Create a new application',
  181. inputSchema: {
  182. type: 'object',
  183. properties: {
  184. name: { type: 'string', description: 'Application name' },
  185. slug: { type: 'string', description: 'Application slug (unique)' },
  186. description: { type: 'string', description: 'Application description' },
  187. organizationId: { type: 'string', description: 'Organization ID' },
  188. repositoryUrl: { type: 'string', description: 'Git repository URL' },
  189. buildCommand: { type: 'string', description: 'Build command' },
  190. startCommand: { type: 'string', description: 'Start command' },
  191. environment: { type: 'object', description: 'Environment variables' },
  192. },
  193. required: ['name', 'slug', 'organizationId'],
  194. },
  195. },
  196. {
  197. name: 'saas_get_application',
  198. description: 'Get application details',
  199. inputSchema: {
  200. type: 'object',
  201. properties: {
  202. id: { type: 'string', description: 'Application ID' },
  203. },
  204. required: ['id'],
  205. },
  206. },
  207. {
  208. name: 'saas_deploy_application',
  209. description: 'Deploy an application',
  210. inputSchema: {
  211. type: 'object',
  212. properties: {
  213. applicationId: { type: 'string', description: 'Application ID' },
  214. version: { type: 'string', description: 'Deployment version' },
  215. commitHash: { type: 'string', description: 'Git commit hash' },
  216. },
  217. required: ['applicationId'],
  218. },
  219. },
  220. {
  221. name: 'saas_get_deployments',
  222. description: 'Get deployment history for an application',
  223. inputSchema: {
  224. type: 'object',
  225. properties: {
  226. applicationId: { type: 'string', description: 'Application ID' },
  227. },
  228. required: ['applicationId'],
  229. },
  230. },
  231. // System tools
  232. {
  233. name: 'saas_health_check',
  234. description: 'Check health of all platform services',
  235. inputSchema: {
  236. type: 'object',
  237. properties: {},
  238. },
  239. },
  240. {
  241. name: 'saas_get_platform_stats',
  242. description: 'Get platform statistics and usage metrics',
  243. inputSchema: {
  244. type: 'object',
  245. properties: {},
  246. },
  247. },
  248. // Storage tools
  249. {
  250. name: 'saas_list_files',
  251. description: 'List files in storage',
  252. inputSchema: {
  253. type: 'object',
  254. properties: {
  255. path: { type: 'string', description: 'Storage path (default: root)' },
  256. recursive: { type: 'boolean', description: 'List files recursively' },
  257. },
  258. },
  259. },
  260. {
  261. name: 'saas_upload_file',
  262. description: 'Upload a file to storage',
  263. inputSchema: {
  264. type: 'object',
  265. properties: {
  266. path: { type: 'string', description: 'Destination path' },
  267. content: { type: 'string', description: 'File content (base64 encoded)' },
  268. contentType: { type: 'string', description: 'MIME content type' },
  269. },
  270. required: ['path', 'content'],
  271. },
  272. },
  273. {
  274. name: 'saas_download_file',
  275. description: 'Download a file from storage',
  276. inputSchema: {
  277. type: 'object',
  278. properties: {
  279. path: { type: 'string', description: 'File path' },
  280. },
  281. required: ['path'],
  282. },
  283. },
  284. {
  285. name: 'saas_delete_file',
  286. description: 'Delete a file from storage',
  287. inputSchema: {
  288. type: 'object',
  289. properties: {
  290. path: { type: 'string', description: 'File path' },
  291. },
  292. required: ['path'],
  293. },
  294. },
  295. ],
  296. };
  297. });
  298. // Handle tool calls
  299. server.setRequestHandler(CallToolRequestSchema, async (request) => {
  300. const { name, arguments: args } = request.params;
  301. try {
  302. switch (name) {
  303. case 'saas_login':
  304. return await handleLogin(args);
  305. case 'saas_logout':
  306. return await handleLogout();
  307. case 'saas_get_current_user':
  308. return await handleGetCurrentUser();
  309. case 'saas_register_user':
  310. return await handleRegisterUser(args);
  311. case 'saas_list_organizations':
  312. return await handleListOrganizations();
  313. case 'saas_create_organization':
  314. return await handleCreateOrganization(args);
  315. case 'saas_get_organization':
  316. return await handleGetOrganization(args);
  317. case 'saas_list_applications':
  318. return await handleListApplications(args);
  319. case 'saas_create_application':
  320. return await handleCreateApplication(args);
  321. case 'saas_get_application':
  322. return await handleGetApplication(args);
  323. case 'saas_deploy_application':
  324. return await handleDeployApplication(args);
  325. case 'saas_get_deployments':
  326. return await handleGetDeployments(args);
  327. case 'saas_health_check':
  328. return await handleHealthCheck();
  329. case 'saas_get_platform_stats':
  330. return await handleGetPlatformStats();
  331. case 'saas_list_files':
  332. return await handleListFiles(args);
  333. case 'saas_upload_file':
  334. return await handleUploadFile(args);
  335. case 'saas_download_file':
  336. return await handleDownloadFile(args);
  337. case 'saas_delete_file':
  338. return await handleDeleteFile(args);
  339. default:
  340. throw new McpError(ErrorCode.MethodNotFound, `Unknown tool: ${name}`);
  341. }
  342. } catch (error) {
  343. if (error instanceof McpError) {
  344. throw error;
  345. }
  346. logger.error(`Tool execution error for ${name}:`, error);
  347. throw new McpError(
  348. ErrorCode.InternalError,
  349. `Tool execution failed: ${error instanceof Error ? error.message : 'Unknown error'}`
  350. );
  351. }
  352. });
  353. // Tool handlers
  354. async function handleLogin(args: { email: string; password: string }) {
  355. try {
  356. const response = await axios.post(`${config.authUrl}/login`, {
  357. email: args.email,
  358. password: args.password,
  359. });
  360. const { user, accessToken, refreshToken } = response.data;
  361. setAuth(accessToken, user);
  362. return {
  363. content: [
  364. {
  365. type: 'text',
  366. text: JSON.stringify({
  367. success: true,
  368. message: `Logged in successfully as ${user.email}`,
  369. user: {
  370. id: user.id,
  371. email: user.email,
  372. firstName: user.firstName,
  373. lastName: user.lastName,
  374. emailVerified: user.emailVerified,
  375. },
  376. }, null, 2),
  377. },
  378. ],
  379. };
  380. } catch (error: any) {
  381. logger.error('Login failed:', error.response?.data || error.message);
  382. throw new McpError(
  383. ErrorCode.Unauthorized,
  384. error.response?.data?.error || 'Login failed'
  385. );
  386. }
  387. }
  388. async function handleLogout() {
  389. if (!authToken) {
  390. return {
  391. content: [
  392. {
  393. type: 'text',
  394. text: JSON.stringify({
  395. success: true,
  396. message: 'Already logged out',
  397. }, null, 2),
  398. },
  399. ],
  400. };
  401. }
  402. try {
  403. await axios.post(`${config.authUrl}/logout`, {}, {
  404. headers: { Authorization: `Bearer ${authToken}` },
  405. });
  406. } catch (error) {
  407. // Continue even if logout request fails
  408. }
  409. clearAuth();
  410. return {
  411. content: [
  412. {
  413. type: 'text',
  414. text: JSON.stringify({
  415. success: true,
  416. message: 'Logged out successfully',
  417. }, null, 2),
  418. },
  419. ],
  420. };
  421. }
  422. async function handleGetCurrentUser() {
  423. if (!authToken) {
  424. throw new McpError(ErrorCode.Unauthorized, 'Not authenticated');
  425. }
  426. try {
  427. const response = await axios.get(`${config.authUrl}/me`, {
  428. headers: { Authorization: `Bearer ${authToken}` },
  429. });
  430. return {
  431. content: [
  432. {
  433. type: 'text',
  434. text: JSON.stringify({
  435. user: response.data,
  436. authenticated: true,
  437. }, null, 2),
  438. },
  439. ],
  440. };
  441. } catch (error: any) {
  442. throw new McpError(
  443. ErrorCode.Unauthorized,
  444. error.response?.data?.error || 'Failed to get user info'
  445. );
  446. }
  447. }
  448. async function handleRegisterUser(args: {
  449. email: string;
  450. password: string;
  451. firstName?: string;
  452. lastName?: string;
  453. }) {
  454. try {
  455. const response = await axios.post(`${config.authUrl}/register`, {
  456. email: args.email,
  457. password: args.password,
  458. firstName: args.firstName,
  459. lastName: args.lastName,
  460. });
  461. return {
  462. content: [
  463. {
  464. type: 'text',
  465. text: JSON.stringify({
  466. success: true,
  467. message: 'User registered successfully',
  468. user: response.data.user,
  469. }, null, 2),
  470. },
  471. ],
  472. };
  473. } catch (error: any) {
  474. throw new McpError(
  475. ErrorCode.InvalidParams,
  476. error.response?.data?.error || 'Registration failed'
  477. );
  478. }
  479. }
  480. async function handleListOrganizations() {
  481. const client = createApiClient();
  482. try {
  483. const response = await client.get('/api/organizations');
  484. return {
  485. content: [
  486. {
  487. type: 'text',
  488. text: JSON.stringify({
  489. organizations: response.data,
  490. }, null, 2),
  491. },
  492. ],
  493. };
  494. } catch (error: any) {
  495. throw new McpError(
  496. ErrorCode.InternalError,
  497. error.response?.data?.error || 'Failed to list organizations'
  498. );
  499. }
  500. }
  501. async function handleCreateOrganization(args: {
  502. name: string;
  503. slug: string;
  504. description?: string;
  505. }) {
  506. const client = createApiClient();
  507. try {
  508. const response = await client.post('/api/organizations', {
  509. name: args.name,
  510. slug: args.slug,
  511. description: args.description,
  512. });
  513. return {
  514. content: [
  515. {
  516. type: 'text',
  517. text: JSON.stringify({
  518. success: true,
  519. message: 'Organization created successfully',
  520. organization: response.data,
  521. }, null, 2),
  522. },
  523. ],
  524. };
  525. } catch (error: any) {
  526. throw new McpError(
  527. ErrorCode.InvalidParams,
  528. error.response?.data?.error || 'Failed to create organization'
  529. );
  530. }
  531. }
  532. async function handleGetOrganization(args: { id: string }) {
  533. const client = createApiClient();
  534. try {
  535. const response = await client.get(`/api/organizations/${args.id}`);
  536. return {
  537. content: [
  538. {
  539. type: 'text',
  540. text: JSON.stringify({
  541. organization: response.data,
  542. }, null, 2),
  543. },
  544. ],
  545. };
  546. } catch (error: any) {
  547. throw new McpError(
  548. ErrorCode.NotFound,
  549. error.response?.data?.error || 'Organization not found'
  550. );
  551. }
  552. }
  553. async function handleListApplications(args: { organizationId: string }) {
  554. const client = createApiClient();
  555. try {
  556. const response = await client.get(`/api/applications?organizationId=${args.organizationId}`);
  557. return {
  558. content: [
  559. {
  560. type: 'text',
  561. text: JSON.stringify({
  562. applications: response.data,
  563. }, null, 2),
  564. },
  565. ],
  566. };
  567. } catch (error: any) {
  568. throw new McpError(
  569. ErrorCode.InternalError,
  570. error.response?.data?.error || 'Failed to list applications'
  571. );
  572. }
  573. }
  574. async function handleCreateApplication(args: {
  575. name: string;
  576. slug: string;
  577. organizationId: string;
  578. description?: string;
  579. repositoryUrl?: string;
  580. buildCommand?: string;
  581. startCommand?: string;
  582. environment?: any;
  583. }) {
  584. const client = createApiClient();
  585. try {
  586. const response = await client.post('/api/applications', {
  587. name: args.name,
  588. slug: args.slug,
  589. organizationId: args.organizationId,
  590. description: args.description,
  591. repositoryUrl: args.repositoryUrl,
  592. buildCommand: args.buildCommand,
  593. startCommand: args.startCommand,
  594. environment: args.environment || {},
  595. });
  596. return {
  597. content: [
  598. {
  599. type: 'text',
  600. text: JSON.stringify({
  601. success: true,
  602. message: 'Application created successfully',
  603. application: response.data,
  604. }, null, 2),
  605. },
  606. ],
  607. };
  608. } catch (error: any) {
  609. throw new McpError(
  610. ErrorCode.InvalidParams,
  611. error.response?.data?.error || 'Failed to create application'
  612. );
  613. }
  614. }
  615. async function handleGetApplication(args: { id: string }) {
  616. const client = createApiClient();
  617. try {
  618. const response = await client.get(`/api/applications/${args.id}`);
  619. return {
  620. content: [
  621. {
  622. type: 'text',
  623. text: JSON.stringify({
  624. application: response.data,
  625. }, null, 2),
  626. },
  627. ],
  628. };
  629. } catch (error: any) {
  630. throw new McpError(
  631. ErrorCode.NotFound,
  632. error.response?.data?.error || 'Application not found'
  633. );
  634. }
  635. }
  636. async function handleDeployApplication(args: {
  637. applicationId: string;
  638. version?: string;
  639. commitHash?: string;
  640. }) {
  641. const client = createApiClient();
  642. try {
  643. const response = await client.post('/api/deployments', {
  644. applicationId: args.applicationId,
  645. version: args.version,
  646. commitHash: args.commitHash,
  647. });
  648. return {
  649. content: [
  650. {
  651. type: 'text',
  652. text: JSON.stringify({
  653. success: true,
  654. message: 'Deployment started successfully',
  655. deployment: response.data,
  656. }, null, 2),
  657. },
  658. ],
  659. };
  660. } catch (error: any) {
  661. throw new McpError(
  662. ErrorCode.InternalError,
  663. error.response?.data?.error || 'Failed to start deployment'
  664. );
  665. }
  666. }
  667. async function handleGetDeployments(args: { applicationId: string }) {
  668. const client = createApiClient();
  669. try {
  670. const response = await client.get(`/api/deployments?applicationId=${args.applicationId}`);
  671. return {
  672. content: [
  673. {
  674. type: 'text',
  675. text: JSON.stringify({
  676. deployments: response.data,
  677. }, null, 2),
  678. },
  679. ],
  680. };
  681. } catch (error: any) {
  682. throw new McpError(
  683. ErrorCode.InternalError,
  684. error.response?.data?.error || 'Failed to get deployments'
  685. );
  686. }
  687. }
  688. async function handleHealthCheck() {
  689. const services = [
  690. { name: 'API Gateway', url: `${config.apiGateway}/health` },
  691. { name: 'Auth Service', url: `${config.authUrl}/health` },
  692. ];
  693. const results = [];
  694. for (const service of services) {
  695. try {
  696. const response = await axios.get(service.url, { timeout: 5000 });
  697. results.push({
  698. name: service.name,
  699. status: 'healthy',
  700. response: response.data,
  701. timestamp: new Date().toISOString(),
  702. });
  703. } catch (error) {
  704. results.push({
  705. name: service.name,
  706. status: 'unhealthy',
  707. error: error instanceof Error ? error.message : 'Unknown error',
  708. timestamp: new Date().toISOString(),
  709. });
  710. }
  711. }
  712. return {
  713. content: [
  714. {
  715. type: 'text',
  716. text: JSON.stringify({
  717. platform_health: results,
  718. overall_status: results.every(r => r.status === 'healthy') ? 'healthy' : 'degraded',
  719. }, null, 2),
  720. },
  721. ],
  722. };
  723. }
  724. async function handleGetPlatformStats() {
  725. // This would typically call an admin endpoint or aggregate data
  726. // For now, return basic information
  727. return {
  728. content: [
  729. {
  730. type: 'text',
  731. text: JSON.stringify({
  732. platform_version: '1.0.0',
  733. services: [
  734. 'Authentication',
  735. 'API Gateway',
  736. 'Database',
  737. 'Redis Cache',
  738. 'File Storage',
  739. 'Real-time WebSocket',
  740. 'Monitoring'
  741. ],
  742. features: [
  743. 'Multi-tenant organizations',
  744. 'Application hosting',
  745. 'TypeScript support',
  746. 'Real-time features',
  747. 'File storage',
  748. 'User management',
  749. 'Deployment management'
  750. ],
  751. timestamp: new Date().toISOString(),
  752. }, null, 2),
  753. },
  754. ],
  755. };
  756. }
  757. async function handleListFiles(args: { path?: string; recursive?: boolean }) {
  758. try {
  759. const response = await axios.get(`${config.storageUrl}/files`, {
  760. params: {
  761. path: args.path || '/',
  762. recursive: args.recursive || false,
  763. },
  764. headers: authToken ? { Authorization: `Bearer ${authToken}` } : {},
  765. });
  766. return {
  767. content: [
  768. {
  769. type: 'text',
  770. text: JSON.stringify({
  771. files: response.data,
  772. path: args.path || '/',
  773. recursive: args.recursive || false,
  774. }, null, 2),
  775. },
  776. ],
  777. };
  778. } catch (error: any) {
  779. throw new McpError(
  780. ErrorCode.InternalError,
  781. error.response?.data?.error || 'Failed to list files'
  782. );
  783. }
  784. }
  785. async function handleUploadFile(args: {
  786. path: string;
  787. content: string;
  788. contentType?: string;
  789. }) {
  790. try {
  791. const response = await axios.post(`${config.storageUrl}/upload`, {
  792. path: args.path,
  793. content: args.content,
  794. contentType: args.contentType || 'application/octet-stream',
  795. }, {
  796. headers: authToken ? { Authorization: `Bearer ${authToken}` } : {},
  797. });
  798. return {
  799. content: [
  800. {
  801. type: 'text',
  802. text: JSON.stringify({
  803. success: true,
  804. message: 'File uploaded successfully',
  805. file: response.data,
  806. }, null, 2),
  807. },
  808. ],
  809. };
  810. } catch (error: any) {
  811. throw new McpError(
  812. ErrorCode.InternalError,
  813. error.response?.data?.error || 'Failed to upload file'
  814. );
  815. }
  816. }
  817. async function handleDownloadFile(args: { path: string }) {
  818. try {
  819. const response = await axios.get(`${config.storageUrl}/download`, {
  820. params: { path: args.path },
  821. headers: authToken ? { Authorization: `Bearer ${authToken}` } : {},
  822. responseType: 'arraybuffer',
  823. });
  824. // Convert to base64 for JSON response
  825. const base64 = Buffer.from(response.data).toString('base64');
  826. return {
  827. content: [
  828. {
  829. type: 'text',
  830. text: JSON.stringify({
  831. path: args.path,
  832. content: base64,
  833. contentType: response.headers['content-type'],
  834. size: response.data.byteLength,
  835. }, null, 2),
  836. },
  837. ],
  838. };
  839. } catch (error: any) {
  840. throw new McpError(
  841. ErrorCode.NotFound,
  842. error.response?.data?.error || 'File not found'
  843. );
  844. }
  845. }
  846. async function handleDeleteFile(args: { path: string }) {
  847. try {
  848. await axios.delete(`${config.storageUrl}/files`, {
  849. data: { path: args.path },
  850. headers: authToken ? { Authorization: `Bearer ${authToken}` } : {},
  851. });
  852. return {
  853. content: [
  854. {
  855. type: 'text',
  856. text: JSON.stringify({
  857. success: true,
  858. message: 'File deleted successfully',
  859. path: args.path,
  860. }, null, 2),
  861. },
  862. ],
  863. };
  864. } catch (error: any) {
  865. throw new McpError(
  866. ErrorCode.NotFound,
  867. error.response?.data?.error || 'File not found'
  868. );
  869. }
  870. }
  871. // Start the MCP server
  872. async function main() {
  873. logger.info('Starting SaaS Platform MCP Server');
  874. const transport = new StdioServerTransport();
  875. await server.connect(transport);
  876. logger.info('SaaS Platform MCP Server connected and ready');
  877. }
  878. // Handle errors
  879. process.on('uncaughtException', (error) => {
  880. logger.error('Uncaught exception:', error);
  881. process.exit(1);
  882. });
  883. process.on('unhandledRejection', (reason, promise) => {
  884. logger.error('Unhandled rejection at:', promise, 'reason:', reason);
  885. process.exit(1);
  886. });
  887. // Start the server
  888. main().catch((error) => {
  889. logger.error('Failed to start MCP server:', error);
  890. process.exit(1);
  891. });