-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathscript.csx
More file actions
1551 lines (1373 loc) · 59.5 KB
/
script.csx
File metadata and controls
1551 lines (1373 loc) · 59.5 KB
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
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
/// <summary>
/// Model Context Protocol (MCP) Custom Code Connector
/// Implements MCP server with AI agent orchestration for Power Platform
/// See readme.md for detailed documentation
/// </summary>
public class Script : ScriptBase
{
// ============================================================================
// DEVELOPER CONFIGURATION: Set to false if using AI agent in existing connector
// ============================================================================
// When true: All operations route to AI agent (standalone MCP connector)
// When false: Only "InvokeMCP" operation uses AI agent (hybrid connector with other API operations)
private const bool AI_AGENT_ONLY = true;
// AI Orchestration Configuration
private const string DEFAULT_BASE_URL = "https://ai-troy2981ai949275546385.openai.azure.com";
private const string DEFAULT_MODEL = "gpt-4o";
private const int DEFAULT_MAX_TOKENS = 16000;
private const double DEFAULT_TEMPERATURE = 0.7;
private const int DEFAULT_MAX_TOOL_CALLS = 10;
// ============================================================================
// DEVELOPER CONFIGURATION: CUSTOMIZE AI BEHAVIOR HERE
// ============================================================================
/// <summary>
/// Define your system instructions here to guide how the AI processes requests.
/// These instructions control the AI's behavior, tone, and approach.
/// Customize this to align with your specific use case and brand voice.
/// </summary>
private string GetSystemInstructions()
{
// ============================================================================
// CUSTOMIZE THESE INSTRUCTIONS FOR YOUR USE CASE
// Define the AI's role, behavior guidelines, response style, and constraints.
// These instructions are sent as the system prompt on every request.
// ============================================================================
return @"
You are an intelligent AI assistant with access to tools and resources through the Model Context Protocol (MCP).
Your Behavior:
- Analyze requests carefully and use available tools to provide accurate, actionable information
- Be clear, concise, and professional in your responses
- When using tools, explain what you're doing and synthesize the results into a coherent response
- If you need more information to complete a request, ask specific clarifying questions
- Cite sources when using resource content in your responses
- Handle errors gracefully and suggest alternative approaches when tools fail
Response Style:
- Use a professional yet approachable tone
- Structure responses with clear sections when appropriate
- Prioritize accuracy over speed - take time to use tools correctly
- Be transparent about limitations and uncertainties";
}
/// <summary>
/// Gets the server information returned during initialization
/// </summary>
private JObject GetServerInfo()
{
return new JObject
{
["name"] = "model-connector-protocol-server",
["version"] = "1.0.0"
};
}
/// <summary>
/// Gets the server capabilities exposed to clients
/// </summary>
private JObject GetServerCapabilities()
{
return new JObject
{
["tools"] = new JObject
{
["listChanged"] = false // Set to true if tools can change at runtime
},
["resources"] = new JObject
{
["subscribe"] = false, // HTTP/HTTPS resources don't support subscriptions
["listChanged"] = false // Set to true if resource list can change at runtime
},
["prompts"] = new JObject
{
["listChanged"] = false // Set to true if prompt list can change at runtime
}
};
}
/// <summary>
/// Defines the MCP tools available through this connector.
/// Add your custom tools here that map to external API operations.
/// Each tool must have: name (string), description (string), and inputSchema (JSON Schema object)
///
/// IMPORTANT: For each tool you add here, you must also implement a corresponding handler method
/// in ExecuteToolByName() with the pattern: Execute{ToolName}Tool(JObject arguments)
///
/// Expected schema format:
/// new JObject
/// {
/// ["name"] = "tool_name",
/// ["description"] = "What this tool does",
/// ["inputSchema"] = new JObject
/// {
/// ["type"] = "object",
/// ["properties"] = new JObject
/// {
/// ["param1"] = new JObject
/// {
/// ["type"] = "string",
/// ["description"] = "Parameter description"
/// }
/// },
/// ["required"] = new JArray { "param1" }
/// }
/// }
/// </summary>
private JArray GetDefinedTools()
{
return new JArray
{
// Add your tools here
};
}
/// <summary>
/// Defines the MCP resources available through this connector.
/// Resources provide read-only access to data via HTTP/HTTPS URLs.
/// Add your custom resources here that map to public web endpoints.
/// Each resource must have: uri (HTTP/HTTPS URL), name (string), description (string), mimeType (string)
///
/// Expected schema format:
/// new JObject
/// {
/// ["uri"] = "https://api.example.com/config/settings.json",
/// ["name"] = "Application Settings",
/// ["description"] = "Current application configuration from API",
/// ["mimeType"] = "application/json"
/// }
/// </summary>
private JArray GetDefinedResources()
{
return new JArray
{
// Add your resources here
};
}
/// <summary>
/// Defines the MCP prompts available through this connector.
/// Prompts are reusable templates with parameters that guide AI interactions.
/// Each prompt must have: name (string), description (string), arguments (array of argument objects)
/// Each argument must have: name (string), description (string), required (boolean)
///
/// Expected schema format:
/// new JObject
/// {
/// ["name"] = "analyze_data",
/// ["description"] = "Analyze data from a specific source",
/// ["arguments"] = new JArray
/// {
/// new JObject
/// {
/// ["name"] = "source",
/// ["description"] = "Data source to analyze",
/// ["required"] = true
/// }
/// }
/// }
/// </summary>
private JArray GetDefinedPrompts()
{
return new JArray
{
// Add your prompts here
};
}
/// <summary>
/// Main entry point for the custom connector
/// Routes requests to either AI Agent mode or traditional MCP mode
/// </summary>
public override async Task<HttpResponseMessage> ExecuteAsync()
{
// Log the incoming operation
this.Context.Logger?.LogInformation($"Connector: Processing operation {this.Context.OperationId}");
// Check if AI agent handles all operations or just InvokeMCP
if (AI_AGENT_ONLY || this.Context.OperationId == "InvokeMCP")
{
return await RouteRequest().ConfigureAwait(false);
}
// For hybrid connectors: Handle other API operations here
// Example:
// switch (this.Context.OperationId)
// {
// case "GetUser":
// return await HandleGetUser().ConfigureAwait(false);
// case "CreateOrder":
// return await HandleCreateOrder().ConfigureAwait(false);
// default:
// break;
// }
// Handle unknown operation
var errorResponse = new HttpResponseMessage(HttpStatusCode.BadRequest);
errorResponse.Content = CreateJsonContent(new JObject
{
["error"] = "Unknown operation",
["message"] = $"Operation '{this.Context.OperationId}' is not supported"
}.ToString());
return errorResponse;
}
/// <summary>
/// Routes requests to appropriate handler based on request format
/// Detects if it's an AI Agent request or traditional MCP JSON-RPC request
/// </summary>
private async Task<HttpResponseMessage> RouteRequest()
{
try
{
var requestBody = await this.Context.Request.Content.ReadAsStringAsync().ConfigureAwait(false);
this.Context.Logger?.LogInformation($"Request Body: {requestBody}");
JObject requestJson;
try
{
requestJson = JObject.Parse(requestBody);
}
catch (JsonException ex)
{
this.Context.Logger?.LogError($"Invalid JSON: {ex.Message}");
return CreateAgentErrorResponse("Invalid JSON in request body", ex.Message, "ValidationError", "INVALID_JSON");
}
// Detect request type: MCP (has jsonrpc) vs Agent (has mode/input)
if (requestJson.ContainsKey("jsonrpc"))
{
// Traditional MCP JSON-RPC request
this.Context.Logger?.LogInformation("Routing to MCP handler");
return await HandleMCPRequest(requestJson).ConfigureAwait(false);
}
else if (requestJson.ContainsKey("mode") || requestJson.ContainsKey("input"))
{
// AI Agent request
this.Context.Logger?.LogInformation("Routing to AI Agent handler");
return await HandleAgentRequest(requestJson).ConfigureAwait(false);
}
else
{
// Ambiguous request - try to infer
if (requestJson.ContainsKey("method"))
{
// Looks like MCP without jsonrpc field - add it and process
requestJson["jsonrpc"] = "2.0";
return await HandleMCPRequest(requestJson).ConfigureAwait(false);
}
else
{
return CreateAgentErrorResponse("Could not determine request type. Include 'mode' for Agent mode or 'jsonrpc' for MCP mode.", null);
}
}
}
catch (Exception ex)
{
this.Context.Logger?.LogError($"Routing error: {ex.Message}\n{ex.StackTrace}");
return CreateAgentErrorResponse($"Request routing failed: {ex.Message}", null);
}
}
/// <summary>
/// Handles MCP JSON-RPC requests
/// Validates the request format and processes MCP protocol methods
/// </summary>
private async Task<HttpResponseMessage> HandleMCPRequest(JObject requestJson)
{
try
{
this.Context.Logger?.LogInformation("Processing MCP request");
// Validate JSON-RPC 2.0 format
var validationError = ValidateJsonRpcRequest(requestJson);
if (validationError != null)
{
return validationError;
}
// Extract method and parameters
string method = requestJson["method"]?.ToString();
var requestId = requestJson["id"];
bool isNotification = requestId == null;
this.Context.Logger?.LogInformation($"MCP Method: {method}, IsNotification: {isNotification}");
// Handle methods locally based on defined tools, resources, and prompts
switch (method)
{
// Lifecycle methods
case "initialize":
return HandleInitialize(requestJson, requestId);
case "initialized":
case "ping":
return CreateSuccessResponse(new JObject(), requestId);
// Tool methods
case "tools/list":
return HandleToolsList(requestId);
case "tools/call":
return await HandleToolsCall(requestJson, requestId).ConfigureAwait(false);
// Resource methods
case "resources/list":
return HandleResourcesList(requestId);
case "resources/read":
return await HandleResourcesRead(requestJson, requestId).ConfigureAwait(false);
case "resources/subscribe":
case "resources/unsubscribe":
// Resource subscriptions are not supported in synchronous Power Platform connectors
return CreateErrorResponse(-32601, "Resource subscriptions not supported. Power Platform connectors are synchronous and cannot maintain persistent connections for push notifications.", requestId);
// Prompt methods
case "prompts/list":
return HandlePromptsList(requestId);
case "prompts/get":
return HandlePromptsGet(requestJson, requestId);
// Completion method (for prompt arguments)
case "completion/complete":
return await HandleCompletionComplete(requestJson, requestId).ConfigureAwait(false);
default:
// For any unhandled methods, return method not found
return CreateErrorResponse(-32601, $"Method not found: {method}", requestId);
}
}
catch (Exception ex)
{
this.Context.Logger?.LogError($"Unexpected error in MCP handler: {ex.Message}");
return CreateErrorResponse(-32603, $"Internal error: {ex.Message}", null);
}
}
/// <summary>
/// Handles AI Agent requests with orchestration and generation capabilities
/// </summary>
private async Task<HttpResponseMessage> HandleAgentRequest(JObject requestJson)
{
var startTime = DateTime.UtcNow;
var executionMetadata = new JObject();
try
{
// Extract request parameters
var input = requestJson["input"]?.ToString();
var options = requestJson["options"] as JObject ?? new JObject();
if (string.IsNullOrEmpty(input))
{
return CreateAgentErrorResponse("'input' field is required", "The request body must include an 'input' field with your question or request.", "ValidationError", "MISSING_INPUT");
}
this.Context.Logger?.LogInformation($"Agent request - Input: {input}");
// Extract options with defaults
var autoExecuteTools = options["autoExecuteTools"]?.Value<bool>() ?? true;
var maxToolCalls = options["maxToolCalls"]?.Value<int>() ?? DEFAULT_MAX_TOOL_CALLS;
var includeToolResults = options["includeToolResults"]?.Value<bool>() ?? true;
var temperature = options["temperature"]?.Value<double>() ?? DEFAULT_TEMPERATURE;
var maxTokens = options["maxTokens"]?.Value<int>() ?? DEFAULT_MAX_TOKENS;
// Get AI model API key from connection parameters
var apiKey = this.Context.Request.Headers.TryGetValues("ai_api_key", out var apiKeyValues)
? apiKeyValues.FirstOrDefault()
: null;
var baseUrl = DEFAULT_BASE_URL;
var model = options["model"]?.ToString();
if (string.IsNullOrEmpty(model) || model == "")
{
model = DEFAULT_MODEL;
}
if (string.IsNullOrEmpty(apiKey))
{
return CreateAgentErrorResponse(
"API key not configured. Please ensure you entered the AI Model API Key when creating the connection.",
"The AI API key should be provided via the connector's connection parameters",
"AuthenticationError",
"MISSING_API_KEY"
);
}
// Call smart agent handler
var agentResponse = await HandleSmartAgent(input, apiKey, model, baseUrl, temperature, maxTokens, autoExecuteTools, maxToolCalls, includeToolResults).ConfigureAwait(false);
// Add metadata
var duration = (DateTime.UtcNow - startTime).TotalSeconds;
agentResponse["metadata"] = new JObject
{
["duration"] = $"{duration:F2}s",
["model"] = model
};
var response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content = CreateJsonContent(agentResponse.ToString());
return response;
}
catch (Exception ex)
{
this.Context.Logger?.LogError($"Agent request error: {ex.Message}\n{ex.StackTrace}");
// Categorize error types
var errorType = "AgentError";
var errorCode = "AGENT_EXECUTION_FAILED";
if (ex.Message.Contains("AI API error"))
{
errorType = "ModelError";
errorCode = "MODEL_API_ERROR";
}
else if (ex.Message.Contains("Tool execution failed"))
{
errorType = "ToolExecutionError";
errorCode = "TOOL_EXECUTION_FAILED";
}
else if (ex.Message.Contains("API key"))
{
errorType = "AuthenticationError";
errorCode = "INVALID_API_KEY";
}
return CreateAgentErrorResponse($"Agent execution failed: {ex.Message}", ex.StackTrace, errorType, errorCode);
}
}
/// <summary>
/// Smart agent handler - Intelligently processes requests with tools
/// </summary>
private async Task<JObject> HandleSmartAgent(string input, string apiKey, string model, string baseUrl, double temperature, int maxTokens, bool autoExecute, int maxToolCalls, bool includeResults)
{
this.Context.Logger?.LogInformation("Smart Agent: Processing request");
// Get available tools
var tools = GetDefinedTools();
// Build system prompt with developer-defined instructions
var systemPrompt = GetSystemInstructions();
// Build messages (stateless - no conversation history)
var messages = new JArray
{
new JObject { ["role"] = "system", ["content"] = systemPrompt },
new JObject { ["role"] = "user", ["content"] = input }
};
// Convert MCP tools to function calling format
var functions = ConvertMCPToolsToFunctions(tools);
// Call AI with function calling
var (aiResponse, executedTools, tokensUsed) = await ExecuteAIWithFunctions(
apiKey, model, baseUrl, messages, functions, temperature, maxTokens, autoExecute, maxToolCalls
).ConfigureAwait(false);
return new JObject
{
["response"] = aiResponse,
["execution"] = new JObject
{
["toolCalls"] = includeResults ? executedTools : new JArray(),
["toolsExecuted"] = executedTools.Count
},
["metadata"] = new JObject
{
["tokensUsed"] = tokensUsed
},
["error"] = null
};
}
/// <summary>
/// Executes AI API call with function calling support (works with OpenAI and Anthropic)
/// </summary>
private async Task<(string response, JArray toolCalls, int tokensUsed)> ExecuteAIWithFunctions(
string apiKey, string model, string baseUrl, JArray messages, JArray functions,
double temperature, int maxTokens, bool autoExecute, int maxIterations)
{
var allToolCalls = new JArray();
var totalTokens = 0;
var iterations = 0;
while (iterations < maxIterations)
{
iterations++;
this.Context.Logger?.LogInformation($"AI API call iteration {iterations}");
// Build request
var requestBody = new JObject
{
["model"] = model,
["messages"] = messages,
["temperature"] = temperature,
["max_tokens"] = maxTokens
};
if (functions != null && functions.Count > 0)
{
requestBody["tools"] = functions;
requestBody["tool_choice"] = "auto";
}
// Call Azure OpenAI API
var apiVersion = "2024-08-01-preview";
var request = new HttpRequestMessage(HttpMethod.Post, $"{baseUrl}/openai/deployments/{model}/chat/completions?api-version={apiVersion}");
request.Headers.Add("api-key", apiKey);
request.Content = new StringContent(requestBody.ToString(), System.Text.Encoding.UTF8, "application/json");
var response = await this.Context.SendAsync(request, this.CancellationToken).ConfigureAwait(false);
var responseBody = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
if (!response.IsSuccessStatusCode)
{
this.Context.Logger?.LogError($"AI API error: {responseBody}");
throw new Exception($"AI API error: {response.StatusCode} - {responseBody}");
}
var responseJson = JObject.Parse(responseBody);
var usage = responseJson["usage"];
totalTokens += usage?["total_tokens"]?.Value<int>() ?? 0;
var choice = responseJson["choices"]?[0];
var message = choice?["message"] as JObject;
var toolCalls = message?["tool_calls"] as JArray;
// If no tool calls, return the response
if (toolCalls == null || toolCalls.Count == 0)
{
var content = message?["content"]?.ToString() ?? "";
return (content, allToolCalls, totalTokens);
}
// Execute tool calls if auto-execute is enabled
if (!autoExecute)
{
return ("Tool calls ready but auto-execute is disabled", allToolCalls, totalTokens);
}
// Add assistant message with tool calls to conversation
messages.Add(message);
// Execute each tool call
foreach (var toolCall in toolCalls)
{
var toolCallId = toolCall["id"]?.ToString();
var function = toolCall["function"] as JObject;
var functionName = function?["name"]?.ToString();
var argumentsStr = function?["arguments"]?.ToString();
this.Context.Logger?.LogInformation($"Executing tool: {functionName}");
JObject arguments;
try
{
arguments = JObject.Parse(argumentsStr);
}
catch
{
arguments = new JObject();
}
// Execute the tool
JObject toolResult;
bool success = true;
string errorMsg = null;
try
{
toolResult = await ExecuteToolByName(functionName, arguments).ConfigureAwait(false);
}
catch (Exception ex)
{
success = false;
errorMsg = ex.Message;
toolResult = new JObject
{
["error"] = ex.Message
};
}
// Record tool call
allToolCalls.Add(new JObject
{
["tool"] = functionName,
["arguments"] = arguments,
["result"] = toolResult,
["success"] = success,
["error"] = errorMsg
});
// Add tool result to conversation
messages.Add(new JObject
{
["role"] = "tool",
["tool_call_id"] = toolCallId,
["content"] = toolResult.ToString()
});
}
// Continue loop to get AI's response after tool execution
}
// Max iterations reached
return ("Max tool call iterations reached", allToolCalls, totalTokens);
}
/// <summary>
/// Executes AI API call without function calling (pure generation)
/// </summary>
private async Task<(string response, int tokensUsed)> ExecuteAICompletion(
string apiKey, string model, string baseUrl, JArray messages, double temperature, int maxTokens)
{
var requestBody = new JObject
{
["model"] = model,
["messages"] = messages,
["temperature"] = temperature,
["max_tokens"] = maxTokens
};
var apiVersion = "2024-08-01-preview";
var request = new HttpRequestMessage(HttpMethod.Post, $"{baseUrl}/openai/deployments/{model}/chat/completions?api-version={apiVersion}");
request.Headers.Add("api-key", apiKey);
request.Content = new StringContent(requestBody.ToString(), System.Text.Encoding.UTF8, "application/json");
var response = await this.Context.SendAsync(request, this.CancellationToken).ConfigureAwait(false);
var responseBody = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
if (!response.IsSuccessStatusCode)
{
this.Context.Logger?.LogError($"AI API error: {responseBody}");
throw new Exception($"AI API error: {response.StatusCode} - {responseBody}");
}
var responseJson = JObject.Parse(responseBody);
var usage = responseJson["usage"];
var totalTokens = usage?["total_tokens"]?.Value<int>() ?? 0;
var content = responseJson["choices"]?[0]?["message"]?["content"]?.ToString() ?? "";
return (content, totalTokens);
}
/// <summary>
/// Converts MCP tool definitions to function calling format (compatible with OpenAI and Anthropic)
/// </summary>
private JArray ConvertMCPToolsToFunctions(JArray mcpTools)
{
var functions = new JArray();
foreach (var tool in mcpTools)
{
var function = new JObject
{
["type"] = "function",
["function"] = new JObject
{
["name"] = tool["name"],
["description"] = tool["description"],
["parameters"] = tool["inputSchema"]
}
};
functions.Add(function);
}
return functions;
}
/// <summary>
/// Executes a tool by name (routes to appropriate tool handler)
/// When you add a new tool to GetDefinedTools(), add its handler here.
/// </summary>
private async Task<JObject> ExecuteToolByName(string toolName, JObject arguments)
{
// Route tool name to handler method
// Add cases here for each tool defined in GetDefinedTools()
switch (toolName)
{
case "get_weather":
return await ExecuteGetWeatherTool(arguments).ConfigureAwait(false);
case "search_data":
return await ExecuteSearchDataTool(arguments).ConfigureAwait(false);
// Add more tool handlers here as you add tools to GetDefinedTools()
// case "your_tool_name":
// return await ExecuteYourToolNameTool(arguments).ConfigureAwait(false);
default:
// This should never be reached due to validation in HandleToolsCall,
// but included for safety
throw new Exception($"Unknown tool: {toolName}");
}
}
/// <summary>
/// Reads a resource by URI (supports HTTP/HTTPS URLs only)
/// </summary>
private async Task<(JObject content, string mimeType)> ReadResourceByUri(string uri)
{
if (!uri.StartsWith("http://") && !uri.StartsWith("https://"))
{
throw new ArgumentException($"Only HTTP/HTTPS URLs are supported. URI: {uri}");
}
try
{
var request = new HttpRequestMessage(HttpMethod.Get, uri);
var response = await this.Context.SendAsync(request, this.CancellationToken).ConfigureAwait(false);
if (!response.IsSuccessStatusCode)
{
throw new Exception($"Failed to fetch resource: {response.StatusCode}");
}
var contentType = response.Content.Headers.ContentType?.MediaType ?? "application/octet-stream";
var content = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
// Try to parse as JSON if content type suggests it
if (contentType.Contains("json"))
{
try
{
var jsonContent = JObject.Parse(content);
return (jsonContent, contentType);
}
catch
{
// If JSON parsing fails, return as text with actual content type
return (new JObject
{
["type"] = "text",
["content"] = content,
["originalContentType"] = contentType
}, contentType);
}
}
// For non-JSON content, determine best representation
// Text-based content types: return as-is with metadata
if (contentType.Contains("text") ||
contentType.Contains("xml") ||
contentType.Contains("html") ||
contentType.Contains("csv"))
{
return (new JObject
{
["type"] = "text",
["content"] = content,
["contentType"] = contentType
}, contentType);
}
// Binary or unknown content: base64 encode or return limited info
return (new JObject
{
["type"] = "binary",
["contentType"] = contentType,
["length"] = content.Length,
["note"] = "Binary content not fully supported in text response"
}, contentType);
}
catch (Exception ex)
{
this.Context.Logger?.LogError($"Error reading resource {uri}: {ex.Message}");
throw new Exception($"Failed to read resource: {ex.Message}", ex);
}
}
/// <summary>
/// Handles the initialize request and returns server capabilities
/// </summary>
private HttpResponseMessage HandleInitialize(JObject requestJson, JToken requestId)
{
this.Context.Logger?.LogInformation("Handling initialize request");
// Extract client info from params if provided
var clientParams = requestJson["params"] as JObject;
var clientInfo = clientParams?["clientInfo"];
var protocolVersion = clientParams?["protocolVersion"]?.ToString() ?? "2025-06-18";
this.Context.Logger?.LogInformation($"Client: {clientInfo}, Protocol: {protocolVersion}");
var result = new JObject
{
["protocolVersion"] = protocolVersion,
["capabilities"] = GetServerCapabilities(),
["serverInfo"] = GetServerInfo()
};
return CreateSuccessResponse(result, requestId);
}
/// <summary>
/// Handles the tools/list request and returns defined tools
/// </summary>
private HttpResponseMessage HandleToolsList(JToken requestId)
{
this.Context.Logger?.LogInformation("Handling tools/list request");
var result = new JObject
{
["tools"] = GetDefinedTools()
};
return CreateSuccessResponse(result, requestId);
}
/// <summary>
/// Handles the tools/call request and executes the specified tool
/// </summary>
private async Task<HttpResponseMessage> HandleToolsCall(JObject requestJson, JToken requestId)
{
this.Context.Logger?.LogInformation("Handling tools/call request");
try
{
var paramsObj = requestJson["params"] as JObject;
if (paramsObj == null)
{
return CreateErrorResponse(-32602, "Invalid params: 'params' object required", requestId);
}
var toolName = paramsObj["name"]?.ToString();
if (string.IsNullOrEmpty(toolName))
{
return CreateErrorResponse(-32602, "Invalid params: 'name' field required", requestId);
}
// Validate arguments is either null or JObject (not other types)
var arguments = paramsObj["arguments"] as JObject;
if (paramsObj.ContainsKey("arguments") && arguments == null && paramsObj["arguments"] != null)
{
return CreateErrorResponse(-32602, "Invalid params: 'arguments' must be an object", requestId);
}
this.Context.Logger?.LogInformation($"Calling tool: {toolName}");
// Check if tool exists in defined tools
var definedTools = GetDefinedTools();
var toolDefinition = definedTools.FirstOrDefault(t => t["name"]?.ToString() == toolName);
if (toolDefinition == null)
{
// Use -32601 (Method not found) for unknown tools per JSON-RPC spec
return CreateErrorResponse(-32601, $"Unknown tool: {toolName}", requestId);
}
// Execute the tool
JObject toolResult;
try
{
toolResult = await ExecuteToolByName(toolName, arguments).ConfigureAwait(false);
// Return successful tool execution result
var result = new JObject
{
["content"] = new JArray
{
new JObject
{
["type"] = "text",
["text"] = toolResult.ToString()
}
}
};
return CreateSuccessResponse(result, requestId);
}
catch (ArgumentException ex)
{
// Invalid parameters provided to tool
this.Context.Logger?.LogError($"Tool '{toolName}' argument error: {ex.Message}");
return CreateErrorResponse(-32602, $"Invalid tool arguments: {ex.Message}", requestId);
}
catch (HttpRequestException ex)
{
// Network/API errors
this.Context.Logger?.LogError($"Tool '{toolName}' network error: {ex.Message}\n{ex.StackTrace}");
return CreateErrorResponse(-32000, $"Tool execution failed due to network error: {ex.Message}", requestId);
}
catch (JsonException ex)
{
// JSON parsing errors
this.Context.Logger?.LogError($"Tool '{toolName}' JSON error: {ex.Message}\n{ex.StackTrace}");
return CreateErrorResponse(-32700, $"Failed to parse tool response: {ex.Message}", requestId);
}
catch (TaskCanceledException ex)
{
// Timeout errors
this.Context.Logger?.LogError($"Tool '{toolName}' timeout: {ex.Message}");
return CreateErrorResponse(-32000, $"Tool execution timed out: {ex.Message}", requestId);
}
catch (Exception ex)
{
// Unexpected errors
this.Context.Logger?.LogError($"Tool '{toolName}' unexpected error: {ex.Message}\n{ex.StackTrace}");
return CreateErrorResponse(-32000, $"Tool execution failed: {ex.Message}", requestId, new JObject
{
["toolName"] = toolName,
["errorType"] = ex.GetType().Name
});
}
}
catch (Exception ex)
{
// Outer catch for any validation errors
this.Context.Logger?.LogError($"Error handling tools/call: {ex.Message}\n{ex.StackTrace}");
return CreateErrorResponse(-32603, $"Internal error: {ex.Message}", requestId);
}
}
/// <summary>
/// Handles the resources/list request and returns defined resources
/// </summary>
private HttpResponseMessage HandleResourcesList(JToken requestId)
{
this.Context.Logger?.LogInformation("Handling resources/list request");
try
{
var result = new JObject
{
["resources"] = GetDefinedResources()
};
return CreateSuccessResponse(result, requestId);
}
catch (Exception ex)
{
this.Context.Logger?.LogError($"Error listing resources: {ex.Message}");
return CreateErrorResponse(-32603, $"Failed to list resources: {ex.Message}", requestId);
}
}
/// <summary>
/// Handles the resources/read request and returns resource contents
/// </summary>
private async Task<HttpResponseMessage> HandleResourcesRead(JObject requestJson, JToken requestId)
{
this.Context.Logger?.LogInformation("Handling resources/read request");
try
{
var paramsObj = requestJson["params"] as JObject;
if (paramsObj == null)
{
return CreateErrorResponse(-32602, "Invalid params: 'params' object required", requestId);
}
var uri = paramsObj["uri"]?.ToString();
if (string.IsNullOrEmpty(uri))
{
return CreateErrorResponse(-32602, "Invalid params: 'uri' field required", requestId);
}
this.Context.Logger?.LogInformation($"Reading resource: {uri}");
// Read the resource via HTTP/HTTPS
JObject resourceContent;
string mimeType;
try
{
(resourceContent, mimeType) = await ReadResourceByUri(uri).ConfigureAwait(false);
}
catch (ArgumentException ex)
{
// Invalid URI (not HTTP/HTTPS)
return CreateErrorResponse(-32602, $"Invalid resource URI: {ex.Message}", requestId);
}
catch (HttpRequestException ex)