@aws/ml-container-creator 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (143) hide show
  1. package/LICENSE +202 -0
  2. package/LICENSE-THIRD-PARTY +68620 -0
  3. package/NOTICE +2 -0
  4. package/README.md +106 -0
  5. package/bin/cli.js +365 -0
  6. package/config/defaults.json +32 -0
  7. package/config/presets/transformers-djl.json +26 -0
  8. package/config/presets/transformers-gpu.json +24 -0
  9. package/config/presets/transformers-lmi.json +27 -0
  10. package/package.json +129 -0
  11. package/servers/README.md +419 -0
  12. package/servers/base-image-picker/catalogs/model-servers.json +1191 -0
  13. package/servers/base-image-picker/catalogs/python-slim.json +38 -0
  14. package/servers/base-image-picker/catalogs/triton-backends.json +51 -0
  15. package/servers/base-image-picker/catalogs/triton.json +38 -0
  16. package/servers/base-image-picker/index.js +495 -0
  17. package/servers/base-image-picker/manifest.json +17 -0
  18. package/servers/base-image-picker/package.json +15 -0
  19. package/servers/hyperpod-cluster-picker/LICENSE +202 -0
  20. package/servers/hyperpod-cluster-picker/index.js +424 -0
  21. package/servers/hyperpod-cluster-picker/manifest.json +14 -0
  22. package/servers/hyperpod-cluster-picker/package.json +17 -0
  23. package/servers/instance-recommender/LICENSE +202 -0
  24. package/servers/instance-recommender/catalogs/instances.json +852 -0
  25. package/servers/instance-recommender/index.js +284 -0
  26. package/servers/instance-recommender/manifest.json +16 -0
  27. package/servers/instance-recommender/package.json +15 -0
  28. package/servers/lib/LICENSE +202 -0
  29. package/servers/lib/bedrock-client.js +160 -0
  30. package/servers/lib/custom-validators.js +46 -0
  31. package/servers/lib/dynamic-resolver.js +36 -0
  32. package/servers/lib/package.json +11 -0
  33. package/servers/lib/schemas/image-catalog.schema.json +185 -0
  34. package/servers/lib/schemas/instances.schema.json +124 -0
  35. package/servers/lib/schemas/manifest.schema.json +64 -0
  36. package/servers/lib/schemas/model-catalog.schema.json +91 -0
  37. package/servers/lib/schemas/regions.schema.json +26 -0
  38. package/servers/lib/schemas/triton-backends.schema.json +51 -0
  39. package/servers/model-picker/catalogs/jumpstart-public.json +66 -0
  40. package/servers/model-picker/catalogs/popular-diffusors.json +88 -0
  41. package/servers/model-picker/catalogs/popular-transformers.json +226 -0
  42. package/servers/model-picker/index.js +1693 -0
  43. package/servers/model-picker/manifest.json +18 -0
  44. package/servers/model-picker/package.json +20 -0
  45. package/servers/region-picker/LICENSE +202 -0
  46. package/servers/region-picker/catalogs/regions.json +263 -0
  47. package/servers/region-picker/index.js +230 -0
  48. package/servers/region-picker/manifest.json +16 -0
  49. package/servers/region-picker/package.json +15 -0
  50. package/src/app.js +1007 -0
  51. package/src/copy-tpl.js +77 -0
  52. package/src/lib/accelerator-validator.js +39 -0
  53. package/src/lib/asset-manager.js +385 -0
  54. package/src/lib/aws-profile-parser.js +181 -0
  55. package/src/lib/bootstrap-command-handler.js +1647 -0
  56. package/src/lib/bootstrap-config.js +238 -0
  57. package/src/lib/ci-register-helpers.js +124 -0
  58. package/src/lib/ci-report-helpers.js +158 -0
  59. package/src/lib/ci-stage-helpers.js +268 -0
  60. package/src/lib/cli-handler.js +529 -0
  61. package/src/lib/comment-generator.js +544 -0
  62. package/src/lib/community-reports-validator.js +91 -0
  63. package/src/lib/config-manager.js +2106 -0
  64. package/src/lib/configuration-exporter.js +204 -0
  65. package/src/lib/configuration-manager.js +695 -0
  66. package/src/lib/configuration-matcher.js +221 -0
  67. package/src/lib/cpu-validator.js +36 -0
  68. package/src/lib/cuda-validator.js +57 -0
  69. package/src/lib/deployment-config-resolver.js +103 -0
  70. package/src/lib/deployment-entry-schema.js +125 -0
  71. package/src/lib/deployment-registry.js +598 -0
  72. package/src/lib/docker-introspection-validator.js +51 -0
  73. package/src/lib/engine-prefix-resolver.js +60 -0
  74. package/src/lib/huggingface-client.js +172 -0
  75. package/src/lib/key-value-parser.js +37 -0
  76. package/src/lib/known-flags-validator.js +200 -0
  77. package/src/lib/manifest-cli.js +280 -0
  78. package/src/lib/mcp-client.js +303 -0
  79. package/src/lib/mcp-command-handler.js +532 -0
  80. package/src/lib/neuron-validator.js +80 -0
  81. package/src/lib/parameter-schema-validator.js +284 -0
  82. package/src/lib/prompt-runner.js +1349 -0
  83. package/src/lib/prompts.js +1138 -0
  84. package/src/lib/registry-command-handler.js +519 -0
  85. package/src/lib/registry-loader.js +198 -0
  86. package/src/lib/rocm-validator.js +80 -0
  87. package/src/lib/schema-validator.js +157 -0
  88. package/src/lib/sensitive-redactor.js +59 -0
  89. package/src/lib/template-engine.js +156 -0
  90. package/src/lib/template-manager.js +341 -0
  91. package/src/lib/validation-engine.js +314 -0
  92. package/src/prompt-adapter.js +63 -0
  93. package/templates/Dockerfile +300 -0
  94. package/templates/IAM_PERMISSIONS.md +84 -0
  95. package/templates/MIGRATION.md +488 -0
  96. package/templates/PROJECT_README.md +439 -0
  97. package/templates/TEMPLATE_SYSTEM.md +243 -0
  98. package/templates/buildspec.yml +64 -0
  99. package/templates/code/chat_template.jinja +1 -0
  100. package/templates/code/flask/gunicorn_config.py +35 -0
  101. package/templates/code/flask/wsgi.py +10 -0
  102. package/templates/code/model_handler.py +387 -0
  103. package/templates/code/serve +300 -0
  104. package/templates/code/serve.py +175 -0
  105. package/templates/code/serving.properties +105 -0
  106. package/templates/code/start_server.py +39 -0
  107. package/templates/code/start_server.sh +39 -0
  108. package/templates/diffusors/Dockerfile +72 -0
  109. package/templates/diffusors/patch_image_api.py +35 -0
  110. package/templates/diffusors/serve +115 -0
  111. package/templates/diffusors/start_server.sh +114 -0
  112. package/templates/do/.gitkeep +1 -0
  113. package/templates/do/README.md +541 -0
  114. package/templates/do/build +83 -0
  115. package/templates/do/ci +681 -0
  116. package/templates/do/clean +811 -0
  117. package/templates/do/config +260 -0
  118. package/templates/do/deploy +1560 -0
  119. package/templates/do/export +306 -0
  120. package/templates/do/logs +319 -0
  121. package/templates/do/manifest +12 -0
  122. package/templates/do/push +119 -0
  123. package/templates/do/register +580 -0
  124. package/templates/do/run +113 -0
  125. package/templates/do/submit +417 -0
  126. package/templates/do/test +1147 -0
  127. package/templates/hyperpod/configmap.yaml +24 -0
  128. package/templates/hyperpod/deployment.yaml +71 -0
  129. package/templates/hyperpod/pvc.yaml +42 -0
  130. package/templates/hyperpod/service.yaml +17 -0
  131. package/templates/nginx-diffusors.conf +74 -0
  132. package/templates/nginx-predictors.conf +47 -0
  133. package/templates/nginx-tensorrt.conf +74 -0
  134. package/templates/requirements.txt +61 -0
  135. package/templates/sample_model/test_inference.py +123 -0
  136. package/templates/sample_model/train_abalone.py +252 -0
  137. package/templates/test/test_endpoint.sh +79 -0
  138. package/templates/test/test_local_image.sh +80 -0
  139. package/templates/test/test_model_handler.py +180 -0
  140. package/templates/triton/Dockerfile +128 -0
  141. package/templates/triton/config.pbtxt +163 -0
  142. package/templates/triton/model.py +130 -0
  143. package/templates/triton/requirements.txt +11 -0
@@ -0,0 +1,284 @@
1
+ #!/usr/bin/env node
2
+ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3
+ // SPDX-License-Identifier: Apache-2.0
4
+
5
+ /**
6
+ * Instance Recommender MCP Server
7
+ *
8
+ * A bundled MCP server that recommends SageMaker instance types and
9
+ * IAM role ARNs based on the current ML framework and model configuration.
10
+ *
11
+ * Supports two modes:
12
+ * - Static (default): Returns hardcoded instance lists by framework category
13
+ * - Smart (--smart flag or BEDROCK_SMART=true): Queries Amazon Bedrock for
14
+ * context-aware recommendations, falling back to static on failure
15
+ *
16
+ * Tool: get_instance_types
17
+ * Accepts: { parameters: string[], limit: number, context: object }
18
+ * Returns: { values: Record<string, string>, choices: Record<string, string[]> }
19
+ */
20
+
21
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
22
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'
23
+ import { z } from 'zod'
24
+ import { readFileSync } from 'node:fs'
25
+ import { fileURLToPath } from 'node:url'
26
+ import { resolve, dirname } from 'node:path'
27
+ import { queryBedrock } from '../lib/bedrock-client.js'
28
+
29
+ // ── Catalog loader ───────────────────────────────────────────────────────────
30
+
31
+ const __filename = fileURLToPath(import.meta.url)
32
+ const __dirname = dirname(__filename)
33
+
34
+ /**
35
+ * Load and parse a JSON catalog file relative to the server directory.
36
+ * Throws on missing file or invalid JSON with the file path in the message.
37
+ *
38
+ * @param {string} relativePath - Path relative to server dir (e.g. './catalogs/instances.json')
39
+ * @returns {any} Parsed JSON content
40
+ */
41
+ function loadCatalog(relativePath) {
42
+ const fullPath = resolve(__dirname, relativePath)
43
+ let raw
44
+ try {
45
+ raw = readFileSync(fullPath, 'utf8')
46
+ } catch (err) {
47
+ throw new Error(`Catalog file not found: ${fullPath}`)
48
+ }
49
+ try {
50
+ return JSON.parse(raw)
51
+ } catch (err) {
52
+ throw new Error(`Failed to parse catalog ${fullPath}: ${err.message}`)
53
+ }
54
+ }
55
+
56
+ // ── Load catalogs from JSON files ─────────────────────────────────────────────
57
+
58
+ let INSTANCE_CATALOG
59
+ let INSTANCE_RECOMMENDATIONS
60
+
61
+ try {
62
+ const data = loadCatalog('./catalogs/instances.json')
63
+ INSTANCE_CATALOG = data.catalog
64
+ INSTANCE_RECOMMENDATIONS = data.recommendations
65
+ } catch (err) {
66
+ process.stderr.write(`[instance-recommender] Fatal: ${err.message}\n`)
67
+ process.exit(1)
68
+ }
69
+
70
+ const GPU_FRAMEWORKS = new Set(['transformers'])
71
+
72
+ // Bedrock configuration
73
+ const SMART_MODE = process.env.BEDROCK_SMART === 'true'
74
+ const BEDROCK_MODEL = process.env.BEDROCK_MODEL || 'global.anthropic.claude-sonnet-4-20250514-v1:0'
75
+ const BEDROCK_REGION = process.env.BEDROCK_REGION || process.env.AWS_REGION || 'us-east-1'
76
+
77
+ /**
78
+ * Per-server configuration passed to the shared Bedrock client.
79
+ */
80
+ const SERVER_CONFIG = {
81
+ serverName: 'instance-recommender',
82
+ systemPromptTemplate: `You are an AWS SageMaker instance type advisor. Given the following ML deployment context, recommend the best SageMaker instance types.
83
+
84
+ Current configuration: {context}
85
+ Requested parameters: {parameters}
86
+ Maximum recommendations per parameter: {limit}
87
+
88
+ Respond with ONLY a JSON object in this exact format, no other text:
89
+ {
90
+ "values": {
91
+ "instanceType": "the single best instance type as a string",
92
+ "awsRoleArn": "a recommended role ARN pattern if applicable"
93
+ }
94
+ }
95
+
96
+ Rules:
97
+ - Only include parameters that were requested
98
+ - For instanceType: recommend real SageMaker instance types (ml.* prefix) appropriate for the framework and model
99
+ - For awsRoleArn: skip this field, do not recommend ARNs
100
+ - The first value in any list should be your top recommendation
101
+ - Consider GPU vs CPU needs based on the framework
102
+ - Consider model size and memory requirements if model info is available
103
+ - Return valid JSON only`,
104
+ temperature: 0.3,
105
+ maxTokens: 1024,
106
+ modelId: BEDROCK_MODEL,
107
+ region: BEDROCK_REGION
108
+ }
109
+
110
+ /**
111
+ * Determine which instance list to use based on framework context and optional search term.
112
+ * When instanceSearch is provided, filters the catalog by keyword matching.
113
+ */
114
+ function getStaticInstances(context) {
115
+ const framework = context?.framework
116
+ const search = context?.instanceSearch
117
+
118
+ // Start with framework-based category filter
119
+ const isGpu = framework && GPU_FRAMEWORKS.has(framework)
120
+ if (!search) {
121
+ // No search term — return the legacy category-based list
122
+ return isGpu ? INSTANCE_RECOMMENDATIONS.gpu : INSTANCE_RECOMMENDATIONS.cpu
123
+ }
124
+
125
+ // Search mode: use the full catalog
126
+ let candidates = Object.entries(INSTANCE_CATALOG)
127
+
128
+ // Tokenize search into lowercase keywords
129
+ const tokens = search.toLowerCase().split(/[\s,\-_]+/).filter(Boolean)
130
+
131
+ // Detect compound terms before tokenization
132
+ const rawLower = search.toLowerCase()
133
+ const wantsMultiGpu = rawLower.includes('multi gpu') || rawLower.includes('multi-gpu') || rawLower.includes('multigpu')
134
+
135
+ // Detect CUDA version requests: "cuda 12", "cuda 11.8", "cuda-12.1"
136
+ const cudaMatch = rawLower.match(/cuda[\s\-_]*(\d+(?:\.\d+)?)/)
137
+ const wantsCudaVersion = cudaMatch ? cudaMatch[1] : null
138
+
139
+ // Score each instance by how many tokens match its tags, accelerator, or instance name
140
+ const scored = candidates.map(([name, meta]) => {
141
+ let score = 0
142
+ const cudaStr = meta.cudaVersions ? meta.cudaVersions.join(' ') : ''
143
+ const haystack = [...meta.tags, meta.accelerator.toLowerCase(), name, meta.category, cudaStr].join(' ')
144
+
145
+ // Compound term: multi-gpu — only match instances with >1 GPU
146
+ if (wantsMultiGpu) {
147
+ if (meta.gpus > 1) {
148
+ score += 5
149
+ } else {
150
+ return { name, meta, score: 0 }
151
+ }
152
+ }
153
+
154
+ // Compound term: cuda version — only match instances supporting that version
155
+ if (wantsCudaVersion) {
156
+ if (!meta.cudaVersions) return { name, meta, score: 0 }
157
+ const hasExact = meta.cudaVersions.includes(wantsCudaVersion)
158
+ const hasMajor = meta.cudaVersions.some(v => v.startsWith(wantsCudaVersion))
159
+ if (hasExact) {
160
+ score += 4
161
+ } else if (hasMajor) {
162
+ score += 3
163
+ } else {
164
+ return { name, meta, score: 0 }
165
+ }
166
+ }
167
+
168
+ for (const token of tokens) {
169
+ // Skip tokens already handled by compound term detection
170
+ if (wantsMultiGpu && (token === 'multi' || token === 'gpu')) continue
171
+ if (wantsCudaVersion && (token === 'cuda' || token === wantsCudaVersion)) continue
172
+
173
+ if (haystack.includes(token)) score += 1
174
+ if (meta.gpus > 1 && (token === 'parallel')) score += 2
175
+ if (token === 'gpu' && meta.gpus > 0) score += 1
176
+ if (token === 'cpu' && meta.gpus === 0) score += 1
177
+ if (token === 'cheap' || token === 'budget' || token === 'cost') {
178
+ if (meta.tags.includes('budget') || meta.tags.includes('cost-effective')) score += 1
179
+ }
180
+ if (token === 'memory' || token === 'high-memory') {
181
+ if (meta.memGb >= 32) score += 1
182
+ }
183
+ if (token === 'large' && meta.vcpus >= 16) score += 1
184
+ // Match specific CUDA versions (e.g. "11.8", "12.1")
185
+ if (meta.cudaVersions && meta.cudaVersions.includes(token)) score += 2
186
+ }
187
+ return { name, meta, score }
188
+ })
189
+
190
+ // Keep only instances with a positive score, sorted descending
191
+ const matched = scored.filter(s => s.score > 0).sort((a, b) => b.score - a.score)
192
+
193
+ if (matched.length === 0) {
194
+ // No matches — fall back to legacy category-based list
195
+ return isGpu ? INSTANCE_RECOMMENDATIONS.gpu : INSTANCE_RECOMMENDATIONS.cpu
196
+ }
197
+
198
+ return matched.map(s => s.name)
199
+ }
200
+
201
+ /**
202
+ * Log to stderr so it doesn't interfere with MCP stdio protocol on stdout.
203
+ */
204
+ function log(message) {
205
+ process.stderr.write(`[instance-recommender] ${message}\n`)
206
+ }
207
+
208
+ // Create MCP server
209
+ const server = new McpServer({
210
+ name: 'instance-recommender',
211
+ version: '1.0.0'
212
+ })
213
+
214
+ // Register the get_instance_types tool
215
+ server.tool(
216
+ 'get_instance_types',
217
+ 'Returns recommended SageMaker instance types and configuration values for ML Container Creator',
218
+ {
219
+ parameters: z.array(z.string()).describe('List of parameter names to provide values for'),
220
+ limit: z.number().int().positive().default(10).describe('Maximum number of choices per parameter'),
221
+ context: z.record(z.string(), z.any()).optional().describe('Current configuration context (framework, modelServer, etc.)')
222
+ },
223
+ async ({ parameters, limit, context }) => {
224
+ const values = {}
225
+ const choices = {}
226
+ let usedSmart = false
227
+
228
+ // Smart mode: try Bedrock first
229
+ if (SMART_MODE && parameters.includes('instanceType')) {
230
+ log('[smart] Smart mode enabled, querying Amazon Bedrock...')
231
+ const bedrockResult = await queryBedrock(SERVER_CONFIG, parameters, limit, context || {})
232
+
233
+ if (bedrockResult?.values?.instanceType) {
234
+ values.instanceType = bedrockResult.values.instanceType
235
+ // Use the Bedrock recommendation as the top choice, pad with static list
236
+ const staticInstances = getStaticInstances(context || {})
237
+ const bedrockValue = bedrockResult.values.instanceType
238
+ const combined = [bedrockValue, ...staticInstances.filter(i => i !== bedrockValue)]
239
+ choices.instanceType = combined.slice(0, limit)
240
+ usedSmart = true
241
+ log(`[smart] Using Bedrock recommendation: ${bedrockValue}`)
242
+ } else {
243
+ log('[smart] Bedrock did not return usable results, falling back to static recommendations')
244
+ }
245
+ }
246
+
247
+ // Static fallback (or non-smart mode)
248
+ if (!usedSmart) {
249
+ for (const param of parameters) {
250
+ if (param === 'instanceType') {
251
+ const instances = getStaticInstances(context || {})
252
+ const limited = instances.slice(0, limit)
253
+ values.instanceType = limited[0]
254
+ choices.instanceType = limited
255
+ }
256
+ // awsRoleArn is left to the user — no default recommendations
257
+ }
258
+ }
259
+
260
+ return {
261
+ content: [{
262
+ type: 'text',
263
+ text: JSON.stringify({ values, choices })
264
+ }]
265
+ }
266
+ }
267
+ )
268
+
269
+ // Export for standalone testing
270
+ export { loadCatalog, getStaticInstances, INSTANCE_CATALOG, INSTANCE_RECOMMENDATIONS, GPU_FRAMEWORKS }
271
+
272
+ // Guard MCP transport — only connect when run as main module
273
+ const isMain = process.argv[1] && resolve(process.argv[1]) === __filename
274
+
275
+ if (isMain) {
276
+ if (SMART_MODE) {
277
+ log(`Smart mode enabled (model: ${BEDROCK_MODEL}, region: ${BEDROCK_REGION})`)
278
+ } else {
279
+ log('Static mode (set BEDROCK_SMART=true to enable Bedrock-powered recommendations)')
280
+ }
281
+
282
+ const transport = new StdioServerTransport()
283
+ await server.connect(transport)
284
+ }
@@ -0,0 +1,16 @@
1
+ {
2
+ "name": "@amzn/ml-container-creator-instance-recommender",
3
+ "version": "1.0.0",
4
+ "description": "MCP server that recommends SageMaker instance types for ML Container Creator.",
5
+ "modes": {
6
+ "static": true,
7
+ "smart": true,
8
+ "discover": false
9
+ },
10
+ "catalogs": {
11
+ "instances": "./catalogs/instances.json"
12
+ },
13
+ "tool": {
14
+ "name": "get_instance_types"
15
+ }
16
+ }
@@ -0,0 +1,15 @@
1
+ {
2
+ "name": "@amzn/ml-container-creator-instance-recommender",
3
+ "private": true,
4
+ "version": "1.0.0",
5
+ "description": "MCP server that recommends SageMaker instance types and IAM role ARNs based on ML framework and model configuration. Supports Bedrock-powered smart recommendations.",
6
+ "type": "module",
7
+ "main": "index.js",
8
+ "license": "Apache-2.0",
9
+ "scripts": {
10
+ "test": "node test.js"
11
+ },
12
+ "dependencies": {
13
+ "@modelcontextprotocol/sdk": "^1.0.0"
14
+ }
15
+ }
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,160 @@
1
+ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ /**
5
+ * Shared Bedrock Client
6
+ *
7
+ * Reusable module that encapsulates Amazon Bedrock LLM invocation,
8
+ * JSON extraction, and fail-fast error handling for bundled MCP servers.
9
+ *
10
+ * Each server passes its own SERVER_CONFIG to queryBedrock() so that
11
+ * system prompts, hyperparameters, and model selection are per-server.
12
+ */
13
+
14
+ /**
15
+ * Extract a JSON object from text that may be raw JSON or wrapped
16
+ * in a markdown-fenced code block (```json ... ```).
17
+ *
18
+ * @param {string} text - Raw LLM response text
19
+ * @returns {object|null} Parsed JSON object, or null if extraction fails
20
+ */
21
+ export function extractJson(text) {
22
+ if (!text || typeof text !== 'string') return null
23
+
24
+ // Try markdown-fenced code block first (```json ... ``` or ``` ... ```)
25
+ const fencedMatch = text.match(/```(?:json)?\s*\n?([\s\S]*?)```/)
26
+ if (fencedMatch) {
27
+ try {
28
+ return JSON.parse(fencedMatch[1].trim())
29
+ } catch {
30
+ // Fall through to raw extraction
31
+ }
32
+ }
33
+
34
+ // Try extracting raw JSON object
35
+ const jsonMatch = text.match(/\{[\s\S]*\}/)
36
+ if (jsonMatch) {
37
+ try {
38
+ return JSON.parse(jsonMatch[0])
39
+ } catch {
40
+ return null
41
+ }
42
+ }
43
+
44
+ return null
45
+ }
46
+
47
+ /**
48
+ * Query Amazon Bedrock for context-aware recommendations.
49
+ * Returns parsed JSON object on success, null on any failure.
50
+ *
51
+ * @param {object} serverConfig - Per-server configuration
52
+ * @param {string} serverConfig.systemPromptTemplate - Prompt template with {context}, {parameters}, {limit} placeholders
53
+ * @param {number} serverConfig.temperature - LLM temperature (0-1)
54
+ * @param {number} serverConfig.maxTokens - Max response tokens
55
+ * @param {string} serverConfig.modelId - Bedrock model ID
56
+ * @param {string} serverConfig.region - AWS region for Bedrock API
57
+ * @param {string} serverConfig.serverName - Server name for log prefixes
58
+ * @param {string[]} parameters - Requested parameter names
59
+ * @param {number} limit - Max choices per parameter
60
+ * @param {object} context - Current configuration context
61
+ * @returns {Promise<{values: object} | null>}
62
+ */
63
+ export async function queryBedrock(serverConfig, parameters, limit, context) {
64
+ const prefix = `[${serverConfig.serverName}]`
65
+
66
+ // Dynamic import with 1s timeout
67
+ let BedrockRuntimeClient, InvokeModelCommand
68
+ try {
69
+ const mod = await Promise.race([
70
+ import('@aws-sdk/client-bedrock-runtime'),
71
+ new Promise((_, reject) =>
72
+ setTimeout(() => reject(new Error('Import timed out')), 1000)
73
+ )
74
+ ])
75
+ BedrockRuntimeClient = mod.BedrockRuntimeClient
76
+ InvokeModelCommand = mod.InvokeModelCommand
77
+ } catch {
78
+ log(prefix, 'Failed to load @aws-sdk/client-bedrock-runtime. Run "npm install" in the servers/lib/ directory')
79
+ return null
80
+ }
81
+
82
+ const client = new BedrockRuntimeClient({
83
+ region: serverConfig.region,
84
+ requestHandler: {
85
+ requestTimeout: 10000
86
+ }
87
+ })
88
+
89
+ // Build prompt from template
90
+ const contextStr = context && Object.keys(context).length > 0
91
+ ? JSON.stringify(context)
92
+ : 'No specific configuration context provided.'
93
+
94
+ const prompt = serverConfig.systemPromptTemplate
95
+ .replace('{context}', contextStr)
96
+ .replace('{parameters}', parameters.join(', '))
97
+ .replace('{limit}', String(limit))
98
+
99
+ try {
100
+ log(prefix, `Querying Bedrock model ${serverConfig.modelId} in ${serverConfig.region}...`)
101
+
102
+ const body = JSON.stringify({
103
+ anthropic_version: 'bedrock-2023-05-31',
104
+ max_tokens: serverConfig.maxTokens,
105
+ temperature: serverConfig.temperature,
106
+ messages: [{
107
+ role: 'user',
108
+ content: prompt
109
+ }]
110
+ })
111
+
112
+ const command = new InvokeModelCommand({
113
+ modelId: serverConfig.modelId,
114
+ contentType: 'application/json',
115
+ accept: 'application/json',
116
+ body
117
+ })
118
+
119
+ const response = await client.send(command)
120
+ const responseBody = JSON.parse(new TextDecoder().decode(response.body))
121
+
122
+ const text = responseBody.content?.[0]?.text
123
+ if (!text) {
124
+ log(prefix, 'Bedrock response contained no text content')
125
+ return null
126
+ }
127
+
128
+ const parsed = extractJson(text)
129
+ if (!parsed) {
130
+ log(prefix, 'Could not extract JSON from Bedrock response')
131
+ return null
132
+ }
133
+
134
+ if (!parsed.values || typeof parsed.values !== 'object') {
135
+ log(prefix, 'Bedrock response missing "values" object')
136
+ return null
137
+ }
138
+
139
+ log(prefix, `Bedrock returned recommendations: ${JSON.stringify(parsed.values)}`)
140
+ return parsed
141
+ } catch (err) {
142
+ if (err.name === 'AccessDeniedException') {
143
+ log(prefix, `Access denied. Ensure bedrock:InvokeModel permission for arn:aws:bedrock:${serverConfig.region}:*:inference-profile/${serverConfig.modelId}`)
144
+ } else if (err.name === 'ResourceNotFoundException') {
145
+ log(prefix, `Model "${serverConfig.modelId}" not found. Set BEDROCK_MODEL env var. Example: BEDROCK_MODEL=global.anthropic.claude-sonnet-4-20250514-v1:0`)
146
+ } else if (err.name === 'ThrottlingException') {
147
+ log(prefix, 'Bedrock rate limit hit. Falling back to static recommendations')
148
+ } else {
149
+ log(prefix, `Bedrock query failed: ${err.name}: ${err.message}`)
150
+ }
151
+ return null
152
+ }
153
+ }
154
+
155
+ /**
156
+ * Log to stderr so it doesn't interfere with MCP stdio protocol on stdout.
157
+ */
158
+ function log(prefix, message) {
159
+ process.stderr.write(`${prefix} ${message}\n`)
160
+ }