Runoob Tutorial ArchiveEnglish

AI Agent Tools and External Integration

AI Agent Tools and External Integration

This chapter introduces how Agents interact with the external world.

Tool calling capability is the key to connecting Agents with external environments.

By integrating various tools, Agents can execute code, access APIs, operate the file system, etc.


Computer Use

Computer Use allows Agents to operate computer interfaces like humans.

This includes graphical interfaces such as browsers and desktop applications.

This is an important step towards achieving Artificial General Intelligence (AGI).

Core Capabilities

Screenshot Parsing: Understanding the content on the screen and identifying interactive elements.

GUI Element Recognition: Identifying interface elements such as buttons, input fields, and menus.

Mouse/Keyboard Control: Simulating human operations, executing actions like clicking and typing.

Browser Automation: Web navigation, form filling, searching, etc.

Working Principle

The workflow of Computer Use can be summarized as: Observe, Understand, Decide, Execute.

First step, screenshot. Capture the content of the current screen or window.

Second step, visual analysis. Use the visual model to analyze the screenshot, identifying interface elements and states.

Third step, decision-making. Decide the next action based on the task goal.

Fourth step, execution. Execute actions such as mouse clicks or keyboard input.

Loop execution until the task is completed.

Code implementation

Basic implementation of Computer Use Agent

class

ComputerUseAgent:

   

"""
Computer Use Agent implementation
capable of operating computer interfaces like a human
"""

   

   

def

init

(

self

,

vision_model

,

action_executor

,

planner

)

:

       

Vision model: Analyze screenshot

       

self

.

vision_model

=

vision_model

       

Action Executor: Executes mouse and keyboard operations

       

self

.

action_executor

=

action_executor

       

Planner: determines the next action

       

self

.

planner

=

planner

       

Maximum execution steps

       

self

.

max_steps

=

100

   

   

def

observe

(

self

,

screenshot

)

:

       

"""
Parse screenshots and identify interactive elements
:param screenshot: Screenshot image
:return: List of interface elements
"""

       

Analyze the screenshot using the visual model

analysis

=

self

.

vision_model

.

analyze

(

screenshot

)

       

       

Return the recognized interface elements

       

Each element includes: type, position, content, interactivity

       

return

analysis.

elements

   

   

def

act

(

self

,

action

)

:

       

"""
Execute action
:param action: Action description, such as {"type": "click", "x": 100, "y": 200}
"""

       

return

self

.

action_executor

.

execute

(

action

)

   

   

def

run

(

self

,

task

)

:

       

"""
Run the task loop
:param task: Task description
:return: Task result
"""

       

Initialize task status

       

self

.

planner

.

set_task

(

task

)

       

       

for

step

in

range

(

self

.

max_steps

)

:

           

Step 1: Capture the current screen

screenshot

=

self

.

get_screen

(

)

           

           

Step two: Observe - Identify interface elements

elements

=

self

.

observe

(

screenshot

)

           

           

Step 3: Decision - Decide the next action

action

=

self

.

planner

.

decide_action

(

elements

)

           

           

Check if the task is completed

           

if

action.

is_final

:

               

return

action.

result

           

           

Step four: Execute action

           

self

.

act

(

action

)

           

           

Optional: Wait for interface update

           

self

.

wait_for_update

(

)

       

       

return

"Maximum step limit reached"

class

VisionModel:

   

"""Vision Model: Analyze Screenshot"""

   

   

def

analyze

(

self

,

screenshot

)

:

       

"""
Analyze the screenshot
Return a list of interface elements
"""

       

Use a multimodal model to analyze

prompt

=

"""
Analyze this screenshot and identify all interactive UI elements.
Including: buttons, input fields, links, menus, etc.

For each element, please provide:

  1. Type (button, input, link, etc.)
  2. Position (bounding box coordinates)
  3. Content (button text, input placeholder, etc.)
  4. Interactivity (visibility, enabled status)
    """

result

=

self

.

vision_model

.

analyze_image

(

screenshot

,

prompt

)

       

return

ScreenAnalysisResult

(

elements

=

result.

elements

)

class

ActionExecutor:

   

"""Action executor: executes mouse and keyboard operations"""

   

   

def

execute

(

self

,

action

)

:

       

"""
Execute action
:param action: Action object
"""

       

if

action.

type

==

"click"

:

           

self

.

mouse

.

click

(

action.

x

,

action.

y

)

       

elif

action.

type

==

"type"

:

           

self

.

keyboard

.

type_text

(

action.

text

)

       

elif

action.

type

==

"scroll"

:

           

self

.

mouse

.

scroll

(

action.

direction

,

action.

amount

)

       

elif

action.

type

==

"press"

:

           

self

.

keyboard

.

press_key

(

action.

key

)

       

       

return

ActionResult

(

success

=

True

)

class

Planner:

   

"""Planner: decides the next action"""

   

   

def

init

(

self

,

llm

)

:

       

self

.

llm

=

llm

       

self

.

task

=

None

       

self

.

history

=

[

]

   

   

def

set_task

(

self

,

task

)

:

       

"""Set the current task"""

       

self

.

task

=

task

       

self

.

history

=

[

]

   

   

def

decide_action

(

self

,

elements

)

:

       

"""
Decide the next action based on the current interface state
"""

prompt

=

f

"""
Current task: {self.task}

Executed history actions:
{self.history}

Interactive elements on the current interface:
{elements}

Please decide the next action.
If the task is complete, return is_final=True.
Otherwise, return the action to be executed (type, coordinates, parameters, etc.).
"""

response

=

self

.

llm

.

generate

(

prompt

)

       

return

Action.

parse

(

response

)

Application scenarios

Computer Use is especially suitable for the following scenarios:

Web automation: such as automatically filling out forms, scraping data, and performing web operations.

Desktop application operations: such as opening files, editing documents, and operating software.

Test automation: such as automatically executing UI tests and regression tests.

Note: Computer Use is still under development and may have issues such as slow execution speed or occasional errors. For scenarios with clear APIs, directly calling the API is usually more efficient than using Computer Use.


Detailed explanation of the MCP protocol

MCP (Model Context Protocol) is an open standard protocol.

It enables AI models to securely connect with external tools and data sources.

The design goal of MCP is to become the "USB interface" in the field of AI.

Core Design Philosophy

Standardization: Unified protocol format, allowing different Agents and tools to be interoperable.

Security: Explicit permission control, ensuring Agents can only access authorized resources.

Scalability: Easy to add new tools and data sources.

Architecture Components

MCP Host: The host environment for running AI applications, such as Claude Desktop or AI coding assistants.

MCP Client: A client that maintains a 1:1 connection with the MCP Server.

MCP Server: The server-side program that provides tools and resources.

Communication Flow

Step 1, Connection Establishment. The Client establishes a connection with the Server and exchanges capability information.

Step 2, Tool Discovery. The Client queries the Server for the tools and resources it provides.

Step 3, Tool Invocation. The Client sends a tool invocation request, the Server executes it and returns the result.

Step 4, Resource Access. The Client can read and write resources provided by the Server.

MCP Server Implementation Example

MCP Server Implementation

from

mcp.

server

import

Server

from

mcp.

types

import

Tool

,

Resource

import

asyncio

Create MCP Server instance

app

=

Server

(

"filesystem"

)

Define filesystem tools

@

app.

list_tools

(

)

async

def

list_tools

(

)

:

   

"List all available tools"

   

return

[

Tool

(

name

=

"read_file"

,

description

=

"Read file content"

,

inputSchema

=

{

               

"type"

:

"object"

,

               

"properties"

:

{

                   

"path"

:

{

                       

"type"

:

"string"

,

                       

"description"

:

"file path"

                   

}

,

                   

"encoding"

:

{

                       

"type"

:

"string"

,

                       

"description"

:

"File encoding, defaults to utf-8"

,

                       

"default"

:

"utf-8"

                   

}

               

}

,

               

"required"

:

[

"path"

]

           

}

       

)

,

Tool

(

name

=

"write_file"

,

description

=

"Write file content"

,

inputSchema

=

{

               

"type"

:

"object"

,

               

"properties"

:

{

                   

"path"

:

{

                       

"type"

:

"string"

,

                       

"description"

:

"File path"

                   

}

,

                   

"content"

:

{

                       

"type"

:

"string"

,

                       

"description"

:

"File content"

                   

}

               

}

,

               

"required"

:

[

"path"

,

"content"

]

           

}

       

)

,

Tool

(

name

=

"list_directory"

,

description

=

"List directory contents"

,

inputSchema

=

{

               

"type"

:

"object"

,

               

"properties"

:

{

                   

"path"

:

{

                       

"type"

:

"string"

,

                       

"description"

:

"Directory path"

                   

}

               

}

           

}

       

)

   

]

@

app.

call_tool

(

)

async

def

call_tool

(

name

,

arguments

)

:

   

"""Execute tool call"""

   

if

name

==

"read_file"

:

       

return

await read_file

(

arguments

[

"path"

]

,

arguments.

get

(

"encoding"

,

"utf-8"

)

)

   

elif

name

==

"write_file"

:

       

return

await write_file

(

arguments

[

"path"

]

,

arguments

[

"content"

]

)

   

elif

name

==

"list_directory"

:

       

return

await list_directory

(

arguments

[

"path"

]

)

   

else

:

       

raise

ValueError

(

f

"Unknown tool: {name}"

)

async

def

read_file

(

path

,

encoding

)

:

   

"""Read file"""

   

with

open

(

path

,

"r"

,

encoding

=

encoding

)

as

f:

        content

=

f.

read

(

)

   

return

[

{

"type"

:

"text"

,

"text"

: content

}

]

async

def

write_file

(

path

,

content

)

:

   

"Write to file"

   

with

open

(

path

,

"w"

,

encoding

=

"utf-8"

)

as

f:

f.

write

(

content

)

   

return

[

{

"type"

:

"text"

,

"text"

:

"File written successfully"

}

]

async

def

list_directory

(

path

)

:

   

List directory

   

import

os

entries

=

os

.

listdir

(

path

)

   

return

[

{

"type"

:

"text"

,

"text"

:

"\n"

.

join

(

entries

)

}

]

Run server

if

name

==

"main"

:

   

import

mcp.

server

.

stdio

    asyncio.

run

(

mcp.

server

.

stdio

.

serve

(

app

)

)


API Integration Modes

There are three common ways for Agents to integrate external APIs.

REST API is the most commonly used Web API style.

GraphQL provides more flexible data querying capabilities.

gRPC is suitable for remote procedure calls in high-performance scenarios.

REST API Integration

REST (Representational State Transfer) is a Web API design style.

Operations are performed using HTTP methods (GET, POST, PUT, DELETE).

REST API client implementation

import

requests

from

typing

import

Dict

,

Any

,

Optional

class

RESTAPIClient:

   

"""
REST API Client
Encapsulates HTTP requests and provides a concise calling interface
"""

   

   

def

init

(

self

,

base_url:

str

,

headers: Optional

[

Dict

]

=

None

)

:

       

"""
Initialize API client
:param base_url: API base URL
:param headers: Default request headers
"""

       

self

.

base_url

=

base_url.

rstrip

(

"/"

)

       

self

.

session

=

requests.

Session

(

)

       

       

Set default request headers

default_headers

=

{

           

"Content-Type"

:

"application/json"

,

           

"Accept"

:

"application/json"

       

}

       

if

headers:

default_headers.

update

(

headers

)

       

self

.

session

.

headers

.

update

(

default_headers

)

   

   

def

call

(

       

self

,

method:

str

,

endpoint:

str

,

params: Optional

[

Dict

]

=

None

,

data: Optional

[

Dict

]

=

None

,

**kwargs

   

)

Dict

[

Any

,

Any

]

:

       

"""
Send API request
:param method: HTTP method (GET, POST, PUT, DELETE)
:param endpoint: API endpoint
:param params: URL query parameters
:param data: request body data
:return: response data
"""

url

=

f

"{self.base_url}/{endpoint.lstrip('/')}"

       

response

=

self

.

session

.

request

(

method

=

method.

upper

(

)

,

url

=

url

,

params

=

params

,

json

=

data

,

**kwargs

       

)

       

       

Check HTTP status code

response.

raise_for_status

(

)

       

       

Parse response

       

if

response.

content

:

           

return

response.

json

(

)

       

return

{

}

   

   

def

get

(

self

,

endpoint:

str

,

params: Optional

[

Dict

]

=

None

)

:

       

"GET request"

       

return

self

.

call

(

"GET"

,

endpoint

,

params

=

params

)

   

   

def

post

(

self

,

endpoint:

str

,

data: Dict

)

:

       

"""POST request"""

       

return

self

.

call

(

"POST"

,

endpoint

,

data

=

data

)

   

   

def

put

(

self

,

endpoint:

str

,

data: Dict

)

:

       

"""PUT request"""

       

return

self

.

call

(

"PUT"

,

endpoint

,

data

=

data

)

   

   

def

delete

(

self

,

endpoint:

str

,

params: Optional

[

Dict

]

=

None

)

:

       

"""DELETE request"""

       

return

self

.

call

(

"DELETE"

,

endpoint

,

params

=

params

)

class

APIAgent:

   

"""
API Agent
Call external APIs using natural language
"""

   

   

def

init

(

self

,

api_client: RESTAPIClient

)

:

       

self

.

api_client

=

api_client

       

self

.

tool_descriptions

=

self

.

define_tools

(

)

   

   

def

define_tools

(

self

)

:

       

"""
Defines the tools available to the Agent
Return tool descriptions for the LLM to understand how to call
"""

       

return

[

           

{

               

"name"

:

"get_weather"

,

               

"description"

:

"Get weather information for a specified city"

,

               

"parameters"

:

{

                   

"type"

:

"object"

,

                   

"properties"

:

{

                       

"city"

:

{

                           

"type"

:

"string"

,

                           

"description"

:

"City name, such as Beijing, Shanghai"

                       

}

                   

}

,

                   

"required"

:

[

"city"

]

               

}

           

}

,

           

{

               

"name"

:

"get_forecast"

,

               

"description"

:

"Get the weather forecast for a specified city"

,

               

"parameters"

:

{

                   

"type"

:

"object"

,

                   

"properties"

:

{

                       

"city"

:

{

                           

"type"

:

"string"

,

                           

"description"

:

"City Name"

                       

}

,

                       

"days"

:

{

                           

"type"

:

"integer"

,

                           

"description"

:

Forecast days, defaults to 3

,

                           

"default"

:

3

                       

}

                   

}

,

                   

"required"

:

[

"city"

]

               

}

           

}

       

]

   

   

def

execute_tool

(

self

,

tool_name:

str

,

arguments: Dict

)

:

       

"""
Execute tool call
:param tool_name: Tool name
:param arguments: Tool parameters
:return: Execution result
"""

       

if

tool_name

==

"get_weather"

:

           

return

self

.

api_client

.

get

(

f

"/weather/{arguments['city']}"

)

       

elif

tool_name

==

"get_forecast"

:

params

=

{

"days"

: arguments.

get

(

"days"

,

3

)

}

           

return

self

.

api_client

.

get

(

f

"/forecast/{arguments['city']}"

,

params

=

params

)

       

else

:

           

raise

ValueError

(

f

"Unknown tool: {tool_name}"

)

API Integration Best Practices

Error Handling: Gracefully handle network errors, timeouts, service unavailability, etc.

Retry Mechanism: Implement exponential backoff retry for transient errors.

Rate Limiting: Adhere to API rate limits to avoid being banned.

Caching Strategy: Implement caching for frequently requested data to reduce API calls.

Security Considerations: Do not hardcode sensitive information like API Keys; use environment variables for management.


Chapter Summary

This chapter introduces the core technologies for Agent interaction with the external world.

Computer Use allows the Agent to operate GUI interfaces, suitable for scenarios requiring interaction with graphical applications.

The MCP protocol provides a standardized way to access tools, serving as the "USB interface" for the Agent era.

API integration is the most common method for integrating with external systems, including REST, GraphQL, and gRPC.

Choosing the appropriate integration method depends on the specific scenario.

For graphical user interface operations, Computer Use is a general solution.

For standardized tool access, MCP is the future direction.

For Web API integration, REST API remains the most mainstream choice.