filesystem-server.vala 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  1. /*
  2. * File System MCP Server Example
  3. *
  4. * This example demonstrates how to create an MCP server that provides
  5. * file system resources. It shows how to use the built-in file system
  6. * resource provider to expose files and directories to MCP clients.
  7. *
  8. * Compile with:
  9. * valac --pkg mcp-vala --pkg json-glib-1.0 --pkg gee-0.8 --pkg posix filesystem-server.vala -o filesystem-server
  10. */
  11. using Mcp;
  12. using Posix;
  13. /**
  14. * File system server that provides resources from a local directory.
  15. */
  16. public class FileSystemServer : GLib.Object {
  17. private Mcp.Core.Server server;
  18. private string root_path;
  19. /**
  20. * Creates a new FileSystemServer.
  21. *
  22. * @param root_path The root directory to serve files from
  23. */
  24. public FileSystemServer (string root_path) {
  25. this.root_path = root_path;
  26. // Create server information
  27. var server_info = new Mcp.Types.Protocol.ServerInfo (
  28. "filesystem-server",
  29. "1.0.0"
  30. );
  31. server_info.description = "MCP server providing file system resources";
  32. // Create server capabilities with resources enabled
  33. var capabilities = new Mcp.Types.Protocol.ServerCapabilities ();
  34. capabilities.logging = true;
  35. capabilities.resources = new Mcp.Types.Protocol.ResourcesCapabilities ();
  36. capabilities.resources.subscribe = true; // Enable resource subscriptions
  37. capabilities.resources.list_changed = true; // Enable list change notifications
  38. // Create the server
  39. server = new Mcp.Core.Server (server_info, capabilities);
  40. // Set up file system resource provider
  41. setup_filesystem_provider ();
  42. }
  43. /**
  44. * Sets up the file system resource provider.
  45. */
  46. private void setup_filesystem_provider () {
  47. // Create a custom file system provider
  48. var provider = new FileSystemResourceProvider (root_path);
  49. // Register the provider with the resource manager
  50. server.resource_manager.register_provider ("file", provider);
  51. // File system provider registered for path: %s
  52. }
  53. /**
  54. * Runs the server.
  55. *
  56. * @return Exit code
  57. */
  58. public async int run () {
  59. try {
  60. // Starting file system MCP server...
  61. // Start the server
  62. bool started = yield server.start ();
  63. if (!started) {
  64. GLib.stderr.printf ("Failed to start server\n");
  65. return 1;
  66. }
  67. // File system server started successfully
  68. // Serving files from: %s
  69. // Waiting for MCP client connections...
  70. // Run the main loop
  71. var main_loop = new MainLoop ();
  72. // Connect shutdown signal
  73. server.shutdown.connect (() => {
  74. main_loop.quit ();
  75. });
  76. main_loop.run ();
  77. return 0;
  78. } catch (Error e) {
  79. GLib.stderr.printf ("Server error: %s\n", e.message);
  80. return 1;
  81. }
  82. }
  83. }
  84. /**
  85. * File system resource provider implementation.
  86. */
  87. public class FileSystemResourceProvider : Mcp.Resources.BaseProvider {
  88. private string root_path;
  89. /**
  90. * Creates a new FileSystemResourceProvider.
  91. *
  92. * @param root_path The root directory to serve files from
  93. */
  94. public FileSystemResourceProvider (string root_path) {
  95. this.root_path = root_path;
  96. }
  97. /**
  98. * {@inheritDoc}
  99. */
  100. public override async Gee.ArrayList<Mcp.Resources.Types.Resource> list_resources (string? cursor) throws Error {
  101. var resources = new Gee.ArrayList<Mcp.Resources.Types.Resource> ();
  102. // List files in root directory
  103. var dir = File.new_for_path (root_path);
  104. if (!dir.query_exists ()) {
  105. throw new Mcp.Core.McpError.RESOURCE_NOT_FOUND ("Directory not found: %s".printf (root_path));
  106. }
  107. var enumerator = yield dir.enumerate_children_async (
  108. "standard::name,standard::type,standard::size,standard::content-type",
  109. FileQueryInfoFlags.NONE,
  110. Priority.DEFAULT,
  111. null
  112. );
  113. FileInfo? file_info = null;
  114. while ((file_info = enumerator.next_file ()) != null) {
  115. if (file_info.get_file_type () == FileType.REGULAR) {
  116. var file = File.new_for_path (Path.build_filename (root_path, file_info.get_name ()));
  117. var resource = new Mcp.Resources.Types.Resource (
  118. file.get_uri (),
  119. file_info.get_name ()
  120. );
  121. resource.description = "File: %s".printf (file_info.get_name ());
  122. // Set MIME type if available
  123. string? content_type = file_info.get_content_type ();
  124. if (content_type != null) {
  125. resource.mime_type = content_type;
  126. } else {
  127. resource.mime_type = guess_mime_type (file_info.get_name ());
  128. }
  129. resource.size = file_info.get_size ();
  130. resources.add (resource);
  131. }
  132. }
  133. return resources;
  134. }
  135. /**
  136. * {@inheritDoc}
  137. */
  138. public override async Gee.ArrayList<Mcp.Types.Common.ResourceContents> read_resource (string uri) throws Error {
  139. var file = File.new_for_uri (uri);
  140. if (!file.query_exists ()) {
  141. throw new Mcp.Core.McpError.RESOURCE_NOT_FOUND ("File not found: %s".printf (uri));
  142. }
  143. uint8[] contents;
  144. string etag;
  145. yield file.load_contents_async (null, out contents, out etag);
  146. // Check if it's text content
  147. string? mime_type = null;
  148. try {
  149. var info = yield file.query_info_async ("standard::content-type", FileQueryInfoFlags.NONE);
  150. mime_type = info.get_content_type ();
  151. } catch (Error e) {
  152. // Ignore error and try to guess from URI
  153. }
  154. var result = new Gee.ArrayList<Mcp.Types.Common.ResourceContents> ();
  155. if (mime_type != null && (mime_type.has_prefix ("text/") || mime_type == "application/json")) {
  156. string text = (string) contents;
  157. result.add (new Mcp.Types.Common.TextResourceContents (uri, text));
  158. } else {
  159. // Return as blob content
  160. result.add (new Mcp.Types.Common.BlobResourceContents (uri, Base64.encode (contents), mime_type ?? "application/octet-stream"));
  161. }
  162. return result;
  163. }
  164. /**
  165. * Guesses MIME type from filename.
  166. *
  167. * @param filename The filename
  168. * @return The guessed MIME type
  169. */
  170. private string guess_mime_type (string filename) {
  171. string extension = "";
  172. var last_dot = filename.last_index_of (".");
  173. if (last_dot != -1) {
  174. extension = filename.substring (last_dot);
  175. }
  176. switch (extension) {
  177. case ".txt":
  178. return "text/plain";
  179. case ".json":
  180. return "application/json";
  181. case ".xml":
  182. return "application/xml";
  183. case ".html":
  184. return "text/html";
  185. case ".css":
  186. return "text/css";
  187. case ".js":
  188. return "application/javascript";
  189. case ".vala":
  190. return "text/x-vala";
  191. case ".c":
  192. case ".h":
  193. return "text/x-c";
  194. case ".png":
  195. return "image/png";
  196. case ".jpg":
  197. case ".jpeg":
  198. return "image/jpeg";
  199. case ".gif":
  200. return "image/gif";
  201. case ".pdf":
  202. return "application/pdf";
  203. default:
  204. return "application/octet-stream";
  205. }
  206. }
  207. }
  208. /**
  209. * Main function.
  210. *
  211. * @param args Command line arguments
  212. * @return Exit code
  213. */
  214. public static int main (string[] args) {
  215. string root_path = ".";
  216. // Parse command line arguments
  217. if (args.length > 1) {
  218. root_path = args[1];
  219. }
  220. // Check if the path exists and is accessible
  221. if (!FileUtils.test (root_path, FileTest.EXISTS | FileTest.IS_DIR)) {
  222. GLib.stderr.printf ("Error: Path '%s' does not exist or is not a directory\n", root_path);
  223. return 1;
  224. }
  225. // Create and run the server
  226. var server = new FileSystemServer (root_path);
  227. // Handle Ctrl+C to gracefully shutdown
  228. // For now, we'll skip signal handling to get the build working
  229. var loop = new MainLoop ();
  230. // Run the server
  231. server.run.begin ((obj, res) => {
  232. loop.quit ();
  233. });
  234. // Keep the main loop running
  235. loop.run ();
  236. return 0;
  237. }