尧图网站设计 尧图网站设计YAOTU DESIGN
ARTICLE DETAIL

资讯详情

深耕网站设计与一线实操的经验洞察。

Julia实现MIT 18.06 线代计算器

Julia实现MIT 18.06 线代计算器 最近又遇到一个跟DeepSeek较劲半天的代码DS写julia实在费劲我又是新学的jl连变量都看不懂就先把目前好不容易搞出来的MCP线代计算器复盘写篇文章留档。目前支持的是MIT 18.06 线代 Linear Algebra 1-3章节的消元-解方程-逆矩阵。大背景是找DS讲题的时候它会在内置的eval_javascript小算草纸上费劲半天抄错数我抄错数查自己算数过程就够头疼了还得查它的更费劲了所以我就搞了个Julia计算器至少不用检查D老师的运算过程了。1. 环境信息组件为何重要版本信息及查看命令Julia整个后端运行的基础$julia --versionjulia version 1.12.6核心包 (ModelContextProtocol.jl)MCP 功能实现API 与版本强相关$ juliajulia ](v1.12) pkg status ModelContextProtocolStatus~/.julia/environments/v1.12/Project.toml[c58f755f] ModelContextProtocol v0.6.1其他依赖包JSON3,LinearAlgebra等[yinyoulocalhost MCP_Server]$ julia --project. -e using Pkg; Pkg.status()Status ~/Julia/MCP_Server/Project.toml[0f8b85d8] JSON3 v1.14.3[c58f755f] ModelContextProtocol v0.6.1[37e2e46d] LinearAlgebra v1.12.0RikkaHubAndroid 客户端与 MCP 协议版本有关版本为2.4.5 / 172MCP 协议版本客户端与服务端通信的“语言”标准ModelContextProtocol.jl支持2025-11-25版本2. 实现代码using ModelContextProtocol using LinearAlgebra, JSON3 #____ 工具矩阵求逆支持任意 n×n 方阵____ function invert_matrix(args::Dict{String, Any}) # 输入格式[[1, 2], [3, 4]] 或 [1 2; 3 4] mat_data to_matrix(args[matrix]) # 如果输入是向量先重塑为矩阵 if typeof(mat_data) Vector{Any} n Int(sqrt(length(mat_data))) A reshape(Float64.(mat_data), n, n) else A Float64.(mat_data) end try invA inv(A) return TextContent(text 逆矩阵是: * JSON3.write(invA)) catch e return TextContent(text 错误矩阵不可逆 - * string(e)) end end # 定义 ToolParameter这里需要 ToolParameter 类型也是位置参数 params [ ToolParameter( matrix, # name array, # type n×n 方阵求逆, # description true, # required nothing # default显式传入nothing ) ] input_schema Dict( type object, properties Dict( matrix Dict( type array, items Dict(type number), description nxn矩阵扁平数组按列优先排列如[a, b, c, d]表示[[a, c], [b, d]] ) ), required [matrix] ) # 工具1: 求逆矩阵 my_tool MCPTool( name invert_matrix, description 计算nxn方阵的逆矩阵, parameters params, input_schema input_schema, # 注意是下划线不是驼峰 handler invert_matrix, return_type TextContent, title nothing, icons nothing, annotations nothing, output_schema nothing, _meta nothing, task_support :none, required_scopes String[] ) #________先清洗个数据非暴露工具______ function to_matrix(data) if data isa Matrix return Float64.(data) end # 检测是否为嵌套结构元组或向量内的向量 if data isa AbstractVector || data isa Tuple # 检查第一个元素是否为容器如果是说明是嵌套结构 if length(data) 0 data[1] isa AbstractVector rows [Float64.(collect(row)) for row in data] return hcat(rows...) # 安全嵌套转换 else # 一维扁平数据 flat Float64.(collect(data)) n Int(round(sqrt(length(flat)))) if n * n ! length(flat) error(无法将长度为 $(length(flat)) 的数据 reshape 为方阵) end return reshape(flat, n, n) end end error(无法解析的矩阵格式: $(typeof(data))) end #____解线性方程组____ function solve_linear_system(args::Dict{String, Any}) A to_matrix(args[A]) b Float64.(args[b]) if length(size(b)) 2 size(b, 2) 1 b vec(b) end try x A \ b return TextContent(text 方程组的解 x * JSON3.write(x)) catch e return TextContent(text 错误方程组无解或矩阵奇异 - * string(e)) end end # 工具2: 解线性方程组 solve_tool MCPTool( name solve_linear_system, description 解线性方程组, parameters [ ToolParameter(A, array, 系数矩阵n×n, true, nothing), ToolParameter(b, array, 右侧向量长度 n, true, nothing) ], input_schema Dict( type object, properties Dict( A Dict( type array, items Dict( type array, items Dict(type number), minItems 1 ), minItems 1, description 系数矩阵 A必须为嵌套数组例如 [[1,2],[3,4]]。不能使用元组或一维数组。 ), b Dict( type array, items Dict(type number), minItems 1, description 右侧向量 b必须为数组例如 [5,6]。 ) ), required [A, b] ), handler solve_linear_system, return_type TextContent, title nothing, icons nothing, annotations nothing, output_schema nothing, _meta nothing, task_support :none, required_scopes String[] ) #____行阶梯形矩阵____ function matrix_rref(args::Dict{String, Any}) # 输入[[1,2,3],[4,5,6],[7,8,9]] A to_matrix(args[matrix]) m, n size(A) R copy(A) lead 1 for r in 1:m if lead n break end i r while R[i, lead] 0 i 1 if i m i r lead 1 if lead n break end end end if lead n break end # 交换行 if i ! r R[[r, i], :] R[[i, r], :] end # 主元归一化 pivot R[r, lead] if pivot ! 0 R[r, :] R[r, :] / pivot end # 消去其他行 for j in 1:m if j ! r R[j, :] R[j, :] - R[j, lead] * R[r, :] end end lead 1 end return TextContent(text 行阶梯形矩阵 (RREF) 为: * JSON3.write(R)) end # 工具3: rref rref_tool MCPTool( name matrix_rref, description 将任意矩阵化为行阶梯形矩阵 (RREF)并返回结果。, parameters [ ToolParameter( matrix, array, 要化为行阶梯形的矩阵例如 [[1,2,3],[4,5,6],[7,8,9]], true, nothing ) ], input_schema Dict( type object, properties Dict( matrix Dict( type array, items Dict( type array, items Dict(type number), minItems 1, description 矩阵的一行 ), minItems 1, description 矩阵必须为嵌套数组例如 [[1,2,3],[4,5,6],[7,8,9]] ) ), required [matrix] ), handler matrix_rref, return_type TextContent, title nothing, icons nothing, annotations nothing, output_schema nothing, _meta nothing, task_support :none, required_scopes String[] ) # 创建服务器并注册工具 server mcp_server( tools [my_tool, solve_tool, rref_tool], # ✅ 三个工具 name Math_Server, version 1.0.0, description 线性代数计算器 ) # 新增配置服务器在 8080 端口监听所有网络接口 # 注意这需要在 start! 之前设置传输层 using ModelContextProtocol: HttpTransport server.transport HttpTransport(host 0.0.0.0, port 8080) connect(server.transport) start!(server)3. 一个完整的工具定义模板: MCPTool() / 参考上面示例我的经验是return_type这一行往后都不用改MCPTool 的位置参数签名因为 ModelContextProtocol.jl 的构造方法是位置参数。ToolParameter 的构造方法五个参数包含 default。input_schema 的 JSON Schema 结构与 ToolParameter 对应但要完整。handler 函数的签名function(args::Dict{String, Any})返回值必须用 TextContent 或 ErrorContent。4. 踩过的坑与解决方案现象原因解决方案MCPToolParameter 报错旧版 API 使用了 MCPToolParameter当前版本已移除改用 ToolParameter并确认参数数量为 5 个含 defaultinputSchema 不被识别参数名应为 input_schema下划线而非驼峰修改为 input_schemaMCPTool 只注册了一个工具只创建了一个 MCPTool 对象为每个函数创建独立的 MCPTool并全部放入 tools 列表手机无法访问 MCP 服务器服务器监听 127.0.0.1 或 localhost改为 0.0.0.0并确认防火墙已放行对应端口文件写入后原内容丢失使用了覆盖模式 “w”未保留原内容改为“读取-修改-写入”模式或检查 data 是否为空段错误Segmentation Fault底层 I/O 操作与 Julia 运行时冲突简化文件操作检查磁盘权限更新 Julia 版本
返回列表