Chinese:【python】样例:Calculator MCP-CSDN博客

Related files:Calculator_MCP:实现简单计算器功能的MCP Server - GitCode

Content

1.Calculator.py

import math
from Logger import logger
class Calculator:
    def __init__(self,ID):
        self.ID=ID
        logger.info('Calculator:'+str(self.ID))
    def plus(self,number_a,number_b):
        result = number_a + number_b
        return result
    def minus(self,number_a,number_b):
        result = number_a - number_b
        return result
    def multiplication(self,number_a,number_b):
        result = number_a * number_b
        return result
    def division(self,number_a,number_b):
        result = number_a / number_b 
        return result
    def sine(self,number_a):
        result = math.sin(number_a)
        return result
    def cosine(self,number_a):
        result = math.cos(number_a)
        return result

2.Calculator_MCP.py

from fastmcp import FastMCP
import datetime
from Calculator import Calculator
from Logger import logger

# Initialize FastMCP server
mcp = FastMCP("Calculator")

calculator_01=Calculator(1)

d=datetime.datetime.now()
T=d.strftime('%Y-%m-%d %H-%M-%S')
T_0=T+'_Calculator_Data'+'.log'


f=open(T_0,mode="at")

# Initialize FastMCP server
mcp = FastMCP("Calculator")

@mcp.tool()
async def plus(a,b)->float:
    """实现两个数的加法,传入参数a和参数b,

    Args:
        a:被加的数
        b:加上的数
    """
    logger.info(f"ID: {calculator_01.ID}, Operation: plus, a: {a}, b: {b}, Result: {calculator_01.plus(a,b)}")
    f.write("{0}+{1}={2}".format(a,b,calculator_01.plus(a,b)))
    return calculator_01.plus(a,b)

@mcp.tool()
async def minus(a,b)->float:
    """实现两个数的减法,传入参数a和参数b,

    Args:
        a:被减的数
        b:减去的数
    """
    logger.info(f"ID: {calculator_01.ID}, Operation: minus, a: {a}, b: {b}, Result: {calculator_01.minus(a,b)}")
    f.write("{0}-{1}={2}".format(a,b,calculator_01.minus(a,b)))
    return calculator_01.minus(a,b)

@mcp.tool()
async def multiplication(a,b)->float:
    """实现两个数的乘法,传入参数a和参数b,

    Args:
        a:被乘的数
        b:乘上的数
    """
    logger.info(f"ID: {calculator_01.ID}, Operation: multiplication, a: {a}, b: {b}, Result: {calculator_01.multiplication(a,b)}")
    f.write("{0}*{1}={2}".format(a,b,calculator_01.multiplication(a,b)))
    return calculator_01.multiplication(a,b)

@mcp.tool()
async def division(a,b)->float:
    """实现两个数的除法,传入参数a和参数b,

    Args:
        a:被除的数
        b:除去的数
    """
    logger.info(f"ID: {calculator_01.ID}, Operation: division, a: {a}, b: {b}, Result: {calculator_01.division(a,b)}")
    f.write("{0}/{1}={2}".format(a,b,calculator_01.division(a,b)))
    return calculator_01.division(a,b)

@mcp.tool()
async def sine(a)->float:
    """计算一个数的正弦,传入参数a,

    Args:
        a:被计算正弦的数(弧度制)
    """
    logger.info(f"ID: {calculator_01.ID}, Operation: sine, a: {a}, Result: {calculator_01.sine(a)}")
    f.write("sin {0}={1}".format(a,calculator_01.sine(a)))
    return calculator_01.sine(a)

@mcp.tool()
async def cosine(a)->float:
    """计算一个数的余弦,传入参数a,

    Args:
        a:被计算余弦的数(弧度制)
    """
    logger.info(f"ID: {calculator_01.ID}, Operation: cosine, a: {a}, Result: {calculator_01.cosine(a)}")
    f.write("cos {0}={1}".format(a,calculator_01.cosine(a)))
    return calculator_01.cosine(a)

if __name__ == "__main__":
    # Initialize and run the server
    logger.info("__main__"+T)
    mcp.run()

3.Logger.py

import logging
import datetime
d=datetime.datetime.now()
T=d.strftime('%Y-%m-%d %H-%M-%S')
T_0=T+'_Calculator_Data'+'.log'


logging.basicConfig(
    level=logging.DEBUG,
    format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
    filename=T_0
)
logger = logging.getLogger(__name__)

Attention

I.Class

1.Definition

Your file must include the following codes:

2.Application

1)Apply For An Object

Your file should include the following codes:

         class <NAME OF THE CLASS>(PARENT CLASS[DEFALT:object]):

             def __init__(self,<INSTANCE VARIABLE1>,<INSTANCE VARIABLE2>,……):

                    self. <INSTANCE VARIABLE1>=<INSTANCE VARIABLE1>

                    self. <INSTANCE VARIABLE2>=<INSTANCE VARIABLE2>

                        ……

               def <INSTANCE METHOD1> (self,PARAMETER1, PARAMETER2,……):

         <SUBJECT OF THE METHOD>

             def <INSTANCE METHOD2> (self,PARAMETER1, PARAMETER2,……):

                 <SUBJECT OF THE METHOD>

                  ......

                  @classmethod

                  def <NAME OF CLASSMETHOD>(PARAMETER1, PARAMETER2,……):

                            <SUBJECT OF THE CLASSMETHOD >

<NAME OF THE OBJECT>=<NAME OF THE CLASS>(<INSTANCE VARIABLE1>,<INSTANCE VARIABLE2>,……)

2)Instance Method And Class Method

Your file should include the following codes:

<NAME OF THE OBJECT>.<INSTANCE METHOD1>(PARAMETER1, PARAMETER2,……)

<NAME OF THE OBJECT>.<INSTANCE METHOD2>(PARAMETER1, PARAMETER2,……)

……

<NAME OF THE OBJECT>.<CLASSMETHOD 1>(PARAMETER1, PARAMETER2,……)

<NAME OF THE OBJECT>.<CLASSMETHOD 2>(PARAMETER1, PARAMETER2,……)

……

II.logger

1.Definition

There are two ways to realize this funcation.One by coding in a new file and then quote it,the other is by coding in the same file.Regarding the convenice in using,

we choose the first project.

2.Application

Your file should include the following codes:

        import logging

        import datetime

最后,求少侠给一个:

免费的关注呗

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐