|
| 1 | +// Copyright (c) 2025, the Dart project authors. Please see the AUTHORS file |
| 2 | +// for details. All rights reserved. Use of this source code is governed by a |
| 3 | +// BSD-style license that can be found in the LICENSE file. |
| 4 | + |
| 5 | +import 'dart:async'; |
| 6 | +import 'dart:convert'; |
| 7 | + |
| 8 | +import 'package:collection/collection.dart'; |
| 9 | +import 'package:dart_mcp/server.dart'; |
| 10 | +import 'package:file/file.dart'; |
| 11 | +import 'package:meta/meta.dart'; |
| 12 | +import 'package:mime/mime.dart'; |
| 13 | +import 'package:package_config/package_config.dart'; |
| 14 | +import 'package:path/path.dart' as p; |
| 15 | + |
| 16 | +import '../utils/analytics.dart'; |
| 17 | +import '../utils/cli_utils.dart'; |
| 18 | +import '../utils/constants.dart'; |
| 19 | +import '../utils/file_system.dart'; |
| 20 | + |
| 21 | +/// Adds a tool for reading package URIs to an MCP server. |
| 22 | +base mixin PackageUriSupport on ToolsSupport, RootsTrackingSupport |
| 23 | + implements FileSystemSupport { |
| 24 | + @override |
| 25 | + FutureOr<InitializeResult> initialize(InitializeRequest request) { |
| 26 | + registerTool(readPackageUris, _readPackageUris); |
| 27 | + return super.initialize(request); |
| 28 | + } |
| 29 | + |
| 30 | + Future<CallToolResult> _readPackageUris(CallToolRequest request) async { |
| 31 | + final args = request.arguments!; |
| 32 | + final validated = validateRootConfig( |
| 33 | + args, |
| 34 | + fileSystem: fileSystem, |
| 35 | + knownRoots: await roots, |
| 36 | + ); |
| 37 | + if (validated.errorResult case final error?) { |
| 38 | + return error; |
| 39 | + } |
| 40 | + // The root is always non-null if there is no error present. |
| 41 | + final root = validated.root!; |
| 42 | + |
| 43 | + // Note that we intentionally do not cache this, because the work to deal |
| 44 | + // with invalidating it would likely be more expensive than just |
| 45 | + // re-discovering it. |
| 46 | + final packageConfig = await findPackageConfig( |
| 47 | + fileSystem.directory(Uri.parse(root.uri)), |
| 48 | + ); |
| 49 | + if (packageConfig == null) { |
| 50 | + return _noPackageConfigFound(root); |
| 51 | + } |
| 52 | + |
| 53 | + final resultContent = <Content>[]; |
| 54 | + for (final uri in (args[ParameterNames.uris] as List).cast<String>()) { |
| 55 | + await for (final content in _readPackageUri( |
| 56 | + Uri.parse(uri), |
| 57 | + packageConfig, |
| 58 | + )) { |
| 59 | + resultContent.add(content); |
| 60 | + } |
| 61 | + } |
| 62 | + |
| 63 | + return CallToolResult(content: resultContent); |
| 64 | + } |
| 65 | + |
| 66 | + Stream<Content> _readPackageUri(Uri uri, PackageConfig packageConfig) async* { |
| 67 | + if (uri.scheme != 'package') { |
| 68 | + yield TextContent(text: 'The URI "$uri" was not a "package:" URI.'); |
| 69 | + return; |
| 70 | + } |
| 71 | + final packageName = uri.pathSegments.first; |
| 72 | + final path = p.url.joinAll(uri.pathSegments.skip(1)); |
| 73 | + final package = packageConfig.packages.firstWhereOrNull( |
| 74 | + (package) => package.name == packageName, |
| 75 | + ); |
| 76 | + if (package == null) { |
| 77 | + yield TextContent( |
| 78 | + text: |
| 79 | + 'The package "$packageName" was not found in your package config, ' |
| 80 | + 'make sure it is listed in your dependencies, or use `pub add` to ' |
| 81 | + 'add it.', |
| 82 | + ); |
| 83 | + return; |
| 84 | + } |
| 85 | + |
| 86 | + if (package.root.scheme != 'file') { |
| 87 | + // We expect all package roots to be file URIs. |
| 88 | + yield Content.text( |
| 89 | + text: |
| 90 | + 'Unexpected root URI for package $packageName ' |
| 91 | + '"${package.root.scheme}", only "file" schemes are supported', |
| 92 | + ); |
| 93 | + return; |
| 94 | + } |
| 95 | + |
| 96 | + final packageRoot = Root(uri: package.root.toString()); |
| 97 | + final resolvedUri = package.packageUriRoot.resolve(path); |
| 98 | + if (!isUnderRoot(packageRoot, resolvedUri.toString(), fileSystem)) { |
| 99 | + yield TextContent( |
| 100 | + text: 'The uri "$uri" attempted to escape it\'s package root.', |
| 101 | + ); |
| 102 | + return; |
| 103 | + } |
| 104 | + |
| 105 | + final osFriendlyPath = p.fromUri(resolvedUri); |
| 106 | + final entityType = await fileSystem.type( |
| 107 | + osFriendlyPath, |
| 108 | + followLinks: false, |
| 109 | + ); |
| 110 | + switch (entityType) { |
| 111 | + case FileSystemEntityType.directory: |
| 112 | + final dir = fileSystem.directory(osFriendlyPath); |
| 113 | + yield Content.text(text: '## Directory "$uri":'); |
| 114 | + await for (final entry in dir.list(followLinks: false)) { |
| 115 | + yield ResourceLink( |
| 116 | + name: p.basename(osFriendlyPath), |
| 117 | + description: entry is Directory ? 'A directory' : 'A file', |
| 118 | + uri: packageConfig.toPackageUri(entry.uri)!.toString(), |
| 119 | + mimeType: lookupMimeType(entry.path) ?? '', |
| 120 | + ); |
| 121 | + } |
| 122 | + case FileSystemEntityType.link: |
| 123 | + // We are only returning a reference to the target, so it is ok to not |
| 124 | + // check the path. The agent may have the permissions to read the linked |
| 125 | + // path on its own, even if it is outside of the package root. |
| 126 | + var targetUri = resolvedUri.resolve( |
| 127 | + await fileSystem.link(osFriendlyPath).target(), |
| 128 | + ); |
| 129 | + // If we can represent it as a package URI, do so. |
| 130 | + final asPackageUri = packageConfig.toPackageUri(targetUri); |
| 131 | + if (asPackageUri != null) { |
| 132 | + targetUri = asPackageUri; |
| 133 | + } |
| 134 | + yield ResourceLink( |
| 135 | + name: p.basename(targetUri.path), |
| 136 | + description: 'Target of symlink at $uri', |
| 137 | + uri: targetUri.toString(), |
| 138 | + mimeType: lookupMimeType(targetUri.path) ?? '', |
| 139 | + ); |
| 140 | + case FileSystemEntityType.file: |
| 141 | + final file = fileSystem.file(osFriendlyPath); |
| 142 | + final mimeType = lookupMimeType(resolvedUri.path) ?? ''; |
| 143 | + final resourceUri = packageConfig.toPackageUri(resolvedUri)!.toString(); |
| 144 | + // Attempt to treat it as a utf8 String first, if that fails then just |
| 145 | + // return it as bytes. |
| 146 | + try { |
| 147 | + yield Content.embeddedResource( |
| 148 | + resource: TextResourceContents( |
| 149 | + uri: resourceUri, |
| 150 | + text: await file.readAsString(), |
| 151 | + mimeType: mimeType, |
| 152 | + ), |
| 153 | + ); |
| 154 | + } catch (_) { |
| 155 | + yield Content.embeddedResource( |
| 156 | + resource: BlobResourceContents( |
| 157 | + uri: resourceUri, |
| 158 | + mimeType: mimeType, |
| 159 | + blob: base64Encode(await file.readAsBytes()), |
| 160 | + ), |
| 161 | + ); |
| 162 | + } |
| 163 | + case FileSystemEntityType.notFound: |
| 164 | + yield TextContent(text: 'File not found: $uri'); |
| 165 | + default: |
| 166 | + yield TextContent( |
| 167 | + text: 'Unsupported file system entity type $entityType', |
| 168 | + ); |
| 169 | + } |
| 170 | + } |
| 171 | + |
| 172 | + CallToolResult _noPackageConfigFound(Root root) => CallToolResult( |
| 173 | + isError: true, |
| 174 | + content: [ |
| 175 | + TextContent( |
| 176 | + text: |
| 177 | + 'No package config found for root ${root.uri}. Have you ran `pub ' |
| 178 | + 'get` in this project?', |
| 179 | + ), |
| 180 | + ], |
| 181 | + )..failureReason = CallToolFailureReason.noPackageConfigFound; |
| 182 | + |
| 183 | + @visibleForTesting |
| 184 | + static final readPackageUris = Tool( |
| 185 | + name: 'read_package_uris', |
| 186 | + description: |
| 187 | + 'Reads "package" scheme URIs which represent paths under the lib ' |
| 188 | + 'directory of Dart package dependencies. Package uris are always ' |
| 189 | + 'relative, and the first segment is the package name. For example, the ' |
| 190 | + 'URI "package:test/test.dart" represents the path "lib/test.dart" under ' |
| 191 | + 'the "test" package. This API supports both reading files and listing ' |
| 192 | + 'directories.', |
| 193 | + inputSchema: Schema.object( |
| 194 | + properties: { |
| 195 | + ParameterNames.uris: Schema.list( |
| 196 | + description: 'All the package URIs to read.', |
| 197 | + items: Schema.string(), |
| 198 | + ), |
| 199 | + ParameterNames.root: rootSchema, |
| 200 | + }, |
| 201 | + required: [ParameterNames.uris, ParameterNames.root], |
| 202 | + ), |
| 203 | + ); |
| 204 | +} |
0 commit comments