-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
142 lines (120 loc) · 5.59 KB
/
Program.cs
File metadata and controls
142 lines (120 loc) · 5.59 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
using System.Text.Json.Nodes;
using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.ChatCompletion;
using Microsoft.SemanticKernel.Connectors.Ollama;
using ModelContextProtocol.SemanticKernel.Extensions;
// Minimal console runner for MongoDB Agent using Semantic Kernel and MCP
class Program
{
static async Task Main(string[] args)
{
// Parse args or environment variables
string ollamaHost = args.Length > 0
? args[0]
: Environment.GetEnvironmentVariable("OLLAMA_HOST") ?? "http://localhost:11434";
string modelId = args.Length > 1 ? args[1] : Environment.GetEnvironmentVariable("OLLAMA_MODEL") ?? "llama3";
string nodePath = args.Length > 2
? args[2]
: Environment.GetEnvironmentVariable("NODE_PATH") ?? "/usr/local/bin/node";
string mcpServerPath = args.Length > 3
? args[3]
: Environment.GetEnvironmentVariable("MCP_SERVER_PATH") ?? "/usr/local/bin/mongodb-mcp-server";
string mongoConn = args.Length > 4
? args[4]
: Environment.GetEnvironmentVariable("MONGO_CONN") ?? "mongodb://localhost:27017";
Console.WriteLine(
$"Ollama Host: {ollamaHost}\nModel: {modelId}\nNode: {nodePath}\nMCP Server: {mcpServerPath}\nMongo Conn: {mongoConn}");
// Build kernel
var builder = Kernel.CreateBuilder();
builder.AddOllamaChatCompletion(modelId, new Uri(ollamaHost));
var kernel = builder.Build();
// Add MCP MongoDB functions
await kernel.Plugins.AddMcpFunctionsFromStdioServerAsync(
"MongoDB",
nodePath,
new[] { mcpServerPath },
environmentVariables: new Dictionary<string, string> { { "MDB_MCP_CONNECTION_STRING", mongoConn } }
);
// List loaded MCP functions
var mcpPlugin = kernel.Plugins.FirstOrDefault(p => p.Name == "MongoDB");
if (mcpPlugin != null)
{
Console.WriteLine($"Loaded {mcpPlugin.Count()} MCP functions:");
foreach (var function in mcpPlugin)
Console.WriteLine($" - {function.Name}: {function.Description}");
}
// Prepare chat
var chatHistory = new ChatHistory();
chatHistory.AddSystemMessage(CreateSystemPrompt(mongoConn));
// User input loo
while (true)
{
Console.Write("\n User Question (enter without qustion to exit): ");
var userInput = Console.ReadLine();
if (string.IsNullOrWhiteSpace(userInput)) break;
chatHistory.AddUserMessage(userInput);
var executionSettings = new OllamaPromptExecutionSettings
{
FunctionChoiceBehavior = FunctionChoiceBehavior.Auto(),
Temperature = 0,
ModelId = modelId,
};
var chatCompletionService = kernel.GetRequiredService<IChatCompletionService>();
var response = await chatCompletionService.GetChatMessageContentAsync(
chatHistory,
executionSettings,
kernel
);
Console.WriteLine($"Answer from LLM:\n{response.Content}\n");
chatHistory.AddAssistantMessage(response.Content ?? "No results available.");
}
}
static string CreateSystemPrompt(string mongoConn)
{
return $@"# MongoDB Query Assistant Agent
You are a specialized AI agent for MongoDB database operations through MCP (Model Context Protocol).
## Your Role
You have direct access to MongoDB database through MCP tools. Your job is to:
1. Understand user requests about MongoDB data
2. Use available MCP tools to query, analyze, and manipulate MongoDB data
3. Present results clearly and concisely in Italian (unless requested otherwise)
## Available MCP Tools
You have access to MongoDB operations including:
- find: Query documents with filters, projections, sorting, and limits
- aggregate: Run aggregation pipelines for complex data analysis
- insert: Add new documents to collections
- update: Modify existing documents
- delete: Remove documents
- listCollections: See available collections
- listDatabases: See available databases
## CRITICAL: Parameter Type Requirements
When calling MCP MongoDB tools, you MUST use correct parameter types:
OBJECT Parameters (filter, sort, projection, update, document, query):
* These MUST be actual JavaScript objects, NOT JSON strings
* CORRECT: filter: {{name: ""John"", age: 25}}
* CORRECT: filter: {{}} (empty object for all documents)
* INCORRECT: filter: ""{{name: 'John'}}""
* INCORRECT: filter: ""{{}}""
* The system will automatically parse JSON strings to objects, but provide objects directly
ARRAY Parameters (pipeline):
* CORRECT: pipeline: [{{$match: {{age: 25}}}}, {{$limit: 10}}]
* INCORRECT: pipeline: ""[{{$match: {{age: 25}}}}]""
NUMBER Parameters (limit, skip, batchSize, maxTimeMS):
* CORRECT: limit: 10
* INCORRECT: limit: ""10""
BOOLEAN Parameters:
* CORRECT: true or false
* INCORRECT: ""true"" or ""false""
## Response Guidelines
1. Always respond in Italian unless the user requests another language
2. If you don't know something, say ""Non lo so"" (I don't know)
3. Execute operations directly using MCP tools - don't just describe what you would do
4. Present query results in a clear, readable format
5. If an operation fails, explain why and suggest corrections
6. Use appropriate indexes and limit results to avoid overwhelming responses
## Database Connection
Active MongoDB connection: {mongoConn}
Remember: You are an ACTION agent - use the tools to actually perform operations, don't just talk about them.
";
}
}