hecate-mcp-server 0.1.0

The Model Context Protocol server for the Hecate simulation code generator!
Documentation
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
use symrs::{BoxExpr, Expr, Symbol};
use hecate_entity::JobConfig;
use hecate_entity::job::{self, JobStatus};
use hecate_entity::job::{Entity as Job, JobScheduler};
use log::{error, info};
use migration::{ExprTrait, Migrator, MigratorTrait};
use rmcp::handler::server::tool::{Parameters, ToolRouter};
use rmcp::{
    ErrorData as McpError, RoleServer, ServiceExt,
    model::{
        CallToolResult, Content, GetPromptRequestParam, GetPromptResult, ListPromptsResult,
        PaginatedRequestParam, Prompt, PromptMessage, PromptMessageContent, PromptMessageRole,
        ServerCapabilities, ServerInfo,
    },
    service::RequestContext,
    tool, transport,
};
use rmcp::{tool_handler, tool_router};
use schemars::JsonSchema;
use sea_orm::prelude::DateTimeUtc;
use sea_orm::{ActiveModelBehavior, Condition, DerivePartialModel, FromQueryResult};
use sea_orm::{
    ActiveModelTrait, ActiveValue::Set, Database, DatabaseConnection, EntityTrait, IntoSimpleExpr,
    QueryFilter,
};
use serde::{Deserialize, Serialize};

use std::collections::HashMap;
pub use std::error::Error as StdError;

trait ToJson {
    fn to_json(&self) -> String;
}

impl<T: Serialize> ToJson for T {
    fn to_json(&self) -> String {
        serde_json::to_string(self).expect("serializable object")
    }
}

#[derive(Clone)]
pub struct HecateSimulator {
    db: DatabaseConnection,
    pub tool_router: ToolRouter<Self>,
}

#[derive(Debug, thiserror::Error)]
pub enum HecateError {
    #[error("couldn't get home dir")]
    NoHomeDir,
}

// impl<E: StdError> From<ExecutorError<E>> for rmcp::Error {
//     fn from(value: ExecutorError<E>) -> Self {
//         rmcp::Error::internal_error(value.to_string(), None)
//     }
// }

#[derive(JsonSchema, Deserialize)]
struct GreetRequest {
    /// Name of the person to greet
    name: String,
}

#[derive(JsonSchema, Deserialize)]
struct JobRequest {
    job_id: i64,
}

/// A request to evaluate a mathematical expression
/// Variables can be supplied to substitute the symbols with values
#[derive(JsonSchema, Deserialize)]
struct EvaluateExprRequest {
    /// Mathematical expression
    expr: String,

    /// Concretized symbol values (optional)
    vars: Option<HashMap<Symbol, BoxExpr>>,
}

#[tool_router]
impl HecateSimulator {
    pub fn db_connection(&self) -> DatabaseConnection {
        self.db.clone()
    }
    pub async fn new() -> anyhow::Result<Self> {
        info!("Initiating Hecate Job Manager");
        let mut dir = dirs::home_dir().ok_or_else(|| HecateError::NoHomeDir)?;
        dir.push(".hecate");
        std::fs::create_dir_all(&dir)?;
        let res = HecateSimulator {
            db: Database::connect(format!("sqlite://{}/hecate.db?mode=rwc", dir.display())).await?,
            tool_router: Self::tool_router(),
        };

        Migrator::up(&res.db, None).await?;

        // Identify jobs that are directly managed by Hecate, without a scheduler, that were
        // interrupted during the last execution, and tag them as such.
        let db = res.db.clone();
        tokio::spawn(async move {
            let mut job = job::ActiveModel::new();
            job.status = Set(JobStatus::Interupted);
            let update_res = Job::update_many().set(job).filter(
                Condition::all()
                    .add(
                        job::Column::Status
                            .into_simple_expr()
                            .in_tuples(JobStatus::unfinished_values()),
                    )
                    .add(job::Column::Scheduler.into_simple_expr().is_null()),
            );

            let update_res = update_res.exec(&db).await;
            match update_res {
                Ok(res) => {
                    info!("Identified {} new interruped jobs", res.rows_affected);
                }
                Err(e) => {
                    error!("Failed to identify interrupted jobs: {}", e);
                }
            }
        });

        // Start status poller for scheduler jobs
        let db = res.db.clone();
        tokio::spawn(async move {
            let unfinished_scheduler_jobs = Job::find().filter(
                Condition::all()
                    .add(
                        job::Column::Status
                            .into_simple_expr()
                            .in_tuples(JobStatus::unfinished_values()),
                    )
                    .add(job::Column::Scheduler.into_simple_expr().is_not_null()),
            );

            let unfinished_scheduler_jobs = unfinished_scheduler_jobs.all(&db).await;

            match &unfinished_scheduler_jobs {
                Ok(jobs) => {
                    info!("Identified {} unfinished scheduler jobs", jobs.len());
                }
                Err(e) => {
                    error!("Failed to identify unfinished scheduler jobs: {}", e);
                    return;
                }
            }
            let unfinished_scheduler_jobs = unfinished_scheduler_jobs.unwrap();

            if unfinished_scheduler_jobs.is_empty() {
                return;
            }
            info!(
                "Starting status pollers for {} unfinished scheduler jobs",
                unfinished_scheduler_jobs.len()
            );

            for job in unfinished_scheduler_jobs {
                let db = db.clone();
                tokio::spawn(async move {
                    let job_id = job.id;
                    let updated_job = job.clone().update_status(&db).await;
                    match updated_job {
                        Ok(job) => {
                            info!("Updated status for job {}", job.id);
                        }
                        Err(e) => {
                            error!("Failed to update status for job {job_id}: {e}");
                            info!("Setting status of job {job_id} to `Failed`");
                            match job.set_status(JobStatus::Failed, &db).await {
                                Ok(job) => info!("Set status `Failed` on job {}", job.id),
                                Err(e) => {
                                    error!("Failed to set status `Failed` on job {job_id} : {e}")
                                }
                            }
                        }
                    }
                });
            }
        });

        Ok(res)
    }
    /// Gets the current weather
    #[tool]
    fn get_weather() -> String {
        "Too hot".into()
    }

    /// Returns the creator's name
    #[tool]
    fn creator_name() -> String {
        "It's a secret ! Just kidding, it's Lyss.".into()
    }

    /// Greets a person
    #[tool]
    fn greet(Parameters(GreetRequest { name }): Parameters<GreetRequest>) -> String {
        format!("Hey there {name}!")
    }

    /// Evaluates a math expression
    #[tool]
    fn evaluate(
        Parameters(EvaluateExprRequest { expr, vars }): Parameters<EvaluateExprRequest>,
    ) -> Result<String, McpError> {
        let expr: Box<dyn Expr> = expr.parse().map_err(|e| {
            McpError::invalid_params(
                format!("Expression couldn't be parsed : {e}"),
                Some(serde_json::Value::String(expr)),
            )
        })?;
        let res = expr.evaluate(vars);
        
        Ok(res.str())
    }

    #[tool(
        description = "Submit a new simulation job. If no number of num_nodes is provided and mpi is set to true in the schema, the number of nodes will be set to the number of available compute nodes.
        By default, don't use mpi when running locally, and don't set debug to true. Finally, make sure the cfl condition is respected.
        Cluster execution requires a scheduler, a cluster_access_name and a cluster name.
        This tool takes care of starting the workflow of the job, ie. compiling and running it.
        If only one node of compute, don't use mpi.
        "
    )]
    pub async fn create_job(
        &self,
        Parameters(job_input): Parameters<JobConfig>,
    ) -> Result<CallToolResult, McpError> {
        let job = Job::new(job_input, &self.db).await?;
        let job_id = job.id;
        let db = self.db.clone();

        tokio::spawn(async move {
            match job.run(&db).await {
                Ok(_) => info!("Successfully initiated job {job_id}"),
                Err(e) => error!("Failed to run job: {e}"),
            }
        });

        Ok(CallToolResult::success(vec![Content::text(format!(
            "id: {}",
            job_id
        ))]))
    }

    #[tool(
        description = "Cancel a simulation job. For example, this can be useful when one wants to make some changes to the input schema, and then recreate a new job with the updated configuration."
    )]
    async fn cancel_job(
        &self,
        Parameters(JobRequest { job_id }): Parameters<JobRequest>,
    ) -> Result<CallToolResult, McpError> {
        let job = Job::find_by_id(job_id)
            .one(&self.db)
            .await
            .map_err(|e| McpError::internal_error(e.to_string(), None))?;
        if job.is_none() {
            return Err(McpError::invalid_request("job not found", None));
        }
        let job = job.unwrap();

        if job.status.is_done() {
            return Err(McpError::invalid_request(
                "job already reached completion",
                Some(
                    serde_json::to_value(job.status).expect("all status variants are serializable"),
                ),
            ));
        }
        if job.status == JobStatus::Canceled {
            return Err(McpError::invalid_request("job already canceled", None));
        }

        let mut job: job::ActiveModel = job.into();
        job.status = Set(JobStatus::Canceled);
        job.update(&self.db)
            .await
            .map_err(|e| McpError::internal_error(e.to_string(), None))?;
        Ok(CallToolResult::success(vec![Content::text(&format!(
            "cancelled job {job_id}"
        ))]))
    }

    #[tool(description = "List unfinished simulation jobs ids and status.")]
    async fn list_unfinished_jobs(&self) -> Result<CallToolResult, McpError> {
        #[derive(DerivePartialModel, FromQueryResult, Serialize)]
        #[sea_orm(entity = "Job")]
        struct JobIdAndStatus {
            id: i64,
            status: JobStatus,
        }

        let sim_jobs = Job::find()
            .filter(
                job::Column::Status
                    .into_simple_expr()
                    .is_in(JobStatus::unfinished_values()),
            )
            .into_partial_model::<JobIdAndStatus>()
            .all(&self.db)
            .await
            .map_err(|e| McpError::internal_error(e.to_string(), None))?;

        Ok(CallToolResult::success(vec![Content::text(
            sim_jobs.to_json(),
        )]))
    }

    #[tool(
        description = "Get partial information about a simulation job (excluding source files and input schema)"
    )]
    pub async fn sim_job_info(
        &self,
        Parameters(JobRequest { job_id }): Parameters<JobRequest>,
    ) -> Result<CallToolResult, McpError> {
        #[derive(FromQueryResult, Serialize, DerivePartialModel)]
        #[sea_orm(entity = "Job")]
        struct JobInfo {
            pub id: i64,
            pub name: String,
            pub created_at: DateTimeUtc,
            // pub schema: Json,
            // pub code: String,
            // pub code_filename: Option<String>,
            // pub cmakelists: Option<String>,
            pub status: JobStatus,
            pub compiler: Option<String>,
            pub cluster_access_name: Option<String>,
            pub scheduler: Option<JobScheduler>,
            pub cluster: Option<String>,
            pub queue: Option<String>,
            pub num_nodes: Option<i32>,
            pub remote_job_id: Option<String>,
        }
        let job_info = Job::find_by_id(job_id)
            .into_partial_model::<JobInfo>()
            .one(&self.db)
            .await
            .map_err(|e| McpError::internal_error(e.to_string(), None))?
            .ok_or_else(|| McpError::resource_not_found("Job not found", None))?;

        Ok(CallToolResult::success(vec![Content::text(
            job_info.to_json(),
        )]))
    }

    #[tool(description = "Get full information about a simulation job (including source files)")]
    pub async fn sim_job_full_info(
        &self,
        Parameters(JobRequest { job_id }): Parameters<JobRequest>,
    ) -> Result<CallToolResult, McpError> {
        let job = Job::find_by_id(job_id)
            .one(&self.db)
            .await
            .map_err(|e| McpError::internal_error(e.to_string(), None))?;

        Ok(CallToolResult::success(vec![Content::text(job.to_json())]))
    }
}

#[tool_handler]
impl rmcp::ServerHandler for HecateSimulator {
    fn get_info(&self) -> ServerInfo {
        ServerInfo {
            instructions: Some("Hecate Simulation Service".into()),
            capabilities: ServerCapabilities::builder()
                .enable_tools()
                .enable_prompts()
                .enable_resources()
                .build(),
            ..Default::default()
        }
    }

    async fn get_prompt(
        &self,
        GetPromptRequestParam { name, arguments: _ }: GetPromptRequestParam,
        _context: RequestContext<RoleServer>,
    ) -> Result<GetPromptResult, McpError> {
        match name.as_str() {
            "system_prompt" => Ok(GetPromptResult {
                description: Some("This is the system prompt for Hecate.".into()),
                messages: vec![PromptMessage {
                    role: PromptMessageRole::User,
                    content: PromptMessageContent::text(
                        "The laplacian operator is available as laplacian. For instance laplacian u is laplacian * u. Derivatives are written with either diff(f, t, 2) or d^2(f)/dt^2. You can also use rounded d which might be better when relevant.",
                    ),
                }],
            }),
            _ => Err(McpError::invalid_params("prompt not found", None)),
        }
    }

    async fn list_prompts(
        &self,
        _request: Option<PaginatedRequestParam>,
        _context: RequestContext<RoleServer>,
    ) -> Result<ListPromptsResult, McpError> {
        Ok(ListPromptsResult {
            next_cursor: None,
            prompts: vec![Prompt::new(
                "system_prompt",
                Some("This is the system prompt for Hecate."),
                None,
            )],
        })
    }
}

pub async fn serve() -> anyhow::Result<()> {
    let service = HecateSimulator::new()
        .await?
        .serve(transport::stdio())
        .await
        .inspect_err(|e| {
            println!("Error starting server: {e}");
        })?;
    service.waiting().await?;

    Ok(())
}