# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
This site has an agentic ask interface you may use to query the documentation dynamically by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.deepcore.top/index.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

---

# Welcome to DeepCore AI

Welcome to DeepCore AI

> *In this document, you'll learn what DeepCore AI is, why DeepCore is the leader in the next generation of web3 AI Agent architectures, as well as its core features and technical architectural strengths, roadmap, and more.*&#x20;
>
> <sup>*<mark style="background-color:yellow;">— Version v2.6, last maintained 5.19.2025, 29</mark>*</sup><sup><mark style="background-color:yellow;">th Revision.<mark style="background-color:yellow;"></sup>

***

<figure><img src="https://1759951032-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvilI5gkHSwBtnpgNfbRd%2Fuploads%2FTfIybFrxgulhNCllIqy5%2Fimage.png?alt=media&amp;token=62b0ef18-a8d5-4129-bdb0-0ecb26e413e7" alt=""><figcaption></figcaption></figure>

## **# The Crisis and Paradigm Shift of Web3 AI Agent** <a href="#the-crisis-and-paradigm-shift-of-web3-ai-agents" id="the-crisis-and-paradigm-shift-of-web3-ai-agents"></a>

#### *AI Agent are hailed as the "redeemer" of the crypto world—a force poised to end outdated narratives and herald a new era for Crypto. Yet, the first-generation Web3 AI Agent ecosystem is mired in structural contradictions:*

1. **Fragmented Ecosystem and Data Silos**
   * The absence of unified infrastructure and decentralized application distribution platforms has led to entrenched "data silos" between AI applications.
   * Projects like #AI16Z, #ARC, #Swarms, and #Myshell attempted to build multi-agent collaboration networks but fell into the trap of "reinventing the wheel" due to reliance on centralized APIs and custom integrations. For instance, #ElizaOS integrated tools like Twitter, Discord, and OpenAI/Claude, yet remained a "stitched-together Web2 stack"—forcing developers to manually adapt APIs and limiting functionality to shallow use cases like prompt engineering, with no capacity for cross-chain interoperability or complex task execution.
2. **Path Dependency on Web2 Mindset**
   * First-generation frameworks (e.g., "wallet + LLM + knowledge base" models) grossly underestimated Web3-native demands, treating blockchain merely as a data storage layer rather than a value-flow network.
   * This architecture spawned two critical failures:
     * **Interoperability Deficits**: The lack of bidirectional interaction protocols between Agent/LLMs required rewriting adaptation layers for each new data source, exploding development costs;
     * **Erosion of Differentiation**: Service frameworks became indistinguishable from Web2 open-source tools, failing to leverage Web3’s composability and decentralization.
3. **Capital Market Reckoning**
   * While Web2 AI innovates at a weekly pace, first-gen Web3 AI Agents stagnated due to lagging technical standards and scenario innovation. The market responded with brutal revaluation: capital abandoned "pseudo-decentralized" projects, seeking true disruptors who grasp Web3-native paradigms.

{% hint style="info" %}
**The direction of breakthrough:**

The Paradigm Leap from “AI+Chain” to “AI-as-Chain”
{% endhint %}

### **# What is DeepCore?**

Evolutionary direction: from “AI+chain” to “AI-as-chain”

\
**I. Overview:**&#x20;

**DeepCore, the next-generation Web3 AI Agent ecosystem based on the MCP protocol, reshaping the landscape of AI and blockchain**

DeepCore is a cutting-edge Web3 AI Agent ecosystem built on the MCP protocol, designed to create a high-performance, trustworthy, and intelligent AI Agent developer platform. It serves as a comprehensive ecosystem platform widely adopted by Web3 users, excelling in tasks such as Crypto project reasoning, analysis, trading, content generation, and more.

We are transforming the outdated landscape of Web AI agents, which has long suffered from weak early-stage ecosystems, difficulties in implementation, and a lack of integration capabilities with critical digital services among most existing AI Agents on the market. We are building an open, composable, and self-evolving ecosystem where everyone can freely assemble, trade, and iterate AI-driven Web3 applications like building with Lego bricks.

As a leader in the next-generation decentralized protocol framework, DeepCore represents a revolutionary breakthrough in AI infrastructure for the Web3 Agent era. It deeply integrates a complete ecosystem of AI Agent developers, creators, users, and blockchain data service providers. The core innovation of DeepCore lies in combining AI Agent development and distribution within a decentralized framework, perfectly aligning with the decentralized ethos of Web3.

<figure><img src="https://1759951032-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvilI5gkHSwBtnpgNfbRd%2Fuploads%2FjcJvOlaje82Db8nuXhh5%2Fimage.png?alt=media&amp;token=690d4f19-28e7-4d6a-9a02-8cdc70de4c0c" alt=""><figcaption></figcaption></figure>

### **II. DeepCore Redefines the Future of AI Collaboration in Crypto**

* **Core Innovation**: Seamlessly integrating AI Agent development, distribution, and decentralized frameworks, fully aligned with Web3 principles;
* **Ecosystem Vision**: Establishing an open, composable, and self-evolving ecosystem where users freely assemble, trade, and iterate AI-powered Web3 applications like building Lego blocks;
* **Industry Transformation**: Addressing critical pain points in existing AI agent ecosystems—fragmented early-stage development, implementation challenges, and lack of integration with key digital services (e.g., multi-chain data, DeFi protocols).

## **III. Join DeepCore, Join the Future of AI** <a href="#ii.-join-deepcore-join-the-future-of-ai" id="ii.-join-deepcore-join-the-future-of-ai"></a>

*/ Real change is only possible when transformative technology meets exceptional talent.*\
*/ And that's just the beginning.*\
*/ Will you be a catalyst or a bystander in this revolution?*

Whether you are a developer, entrepreneur, or Web3 enthusiast, DeepCore offers:

* **Developers**: Frictionless AI Agent development environments and sustainable revenue models.
* **Enterprises**: Compliant on-chain AI deployment and precise user targeting.
* **Users**: The superpower to build intelligent applications through natural language.

The future is now - DeepCore is building not just a technology protocol and ecological platform, but a bridge to a symbiotic civilization of Crypto enthusiasts, participants and AI. Here, every idea is amplified by AI, every interaction creates value, and together we are the makers of a new world.


# Competitive advantages

## # W*hy DeepCore is the leader in the next generation of web3 AI Agent architectures?*

<figure><img src="https://1759951032-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvilI5gkHSwBtnpgNfbRd%2Fuploads%2FPblDGmS78i8PAhjULqK3%2FBanner2.png?alt=media&amp;token=06fe285a-e1f1-49df-9d6a-381f7220e95f" alt=""><figcaption><p>DeepCore</p></figcaption></figure>

### **We are committed to: Redefining the Foundational Paradigm of Web3 AI Agents and Building the Future of Composable Intelligent Agents**

DeepCore already supports most of the major LLMs on the market.

<figure><img src="https://1759951032-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvilI5gkHSwBtnpgNfbRd%2Fuploads%2FyQHjvWmmWBSCSO6NcXAh%2FLLms.png?alt=media&amp;token=2bd55dc4-49cc-46ef-8dc8-c5b06335ef67" alt=""><figcaption></figcaption></figure>

***

DeepCore outperforms platforms like #Eliza,  #ARC, #Swarms, and #Myshell with two key strengths(MCP & Deep Research), focusing on robust infrastructure:

* <mark style="background-color:yellow;">**Quick Integration: Seamlessly integrates MCP services from CMC and CoinGecko.**</mark>
* <mark style="background-color:yellow;">**Service Deployment: Publishes its interfaces as MCP services for enhanced functionality.**</mark>

## **I. Technical Paradigm Shift**

DeepCore establishes the foundational OS for Web3 AI Agents, evolving from single-purpose tools to autonomous collaborative networks through:\
• Protocol-native MCP integration\
• Distributed node architecture\
• Incentive-aligned economic design

This transition from "AI+Chain" to "AI-as-Chain" delivers scalable, secure and equitable infrastructure, empowering developers to unlock the next wave of blockchain-AI convergence.

<figure><img src="https://1759951032-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvilI5gkHSwBtnpgNfbRd%2Fuploads%2FsqyCGvjxIRPqvrN0GRzQ%2Fimage.png?alt=media&amp;token=11caea20-7d4a-480c-931d-78709979ff27" alt=""><figcaption></figcaption></figure>

## **II. Core Innovations**

1. **Eliminating "Pseudo-Decentralization"**\
   Web3-Native Architecture: DeepCore moves beyond Web2 tech stacks to build a decentralized-first AI Agent infrastructure, ensuring data sovereignty and protocol autonomy.
2. **MCP Protocol: The Universal Cross-Chain Interface**\
   • Protocol Leadership: First fully MCP-compatible ecosystem standardizing data interoperability\
   • Technical Scalability: Seamless EVM (Ethereum, Base...) and non-EVM (Solana, Aptos) integration covering 90% of third-party on-chain scenarios
3. **Deep Research Engine: On-Chain Intelligence Core**\
   Advanced task execution integrating Gemini, GPT, DeepCore and Claude models for multi-stage workflows:\
   Data Collection → Analysis → Decision → Execution
4. **Developer Revolution: Efficiency Breakthroughs**\
   • Natural Language Coding: Describe tasks (e.g. "Monitor trending Memecoins with 100% take-profit auto-trading") → AI generates executable code (10 days → 1 hour)\
   • Visual Orchestration: Drag-and-drop modules (on-chain monitoring/MEV defense) with 80% efficiency gain (testnet verified)
5. **Economic Model: Ecosystem Flywheel (**&#x54;he Token Economics book is the final wor&#x64;**)**\
   Incentive alignment:

* Developers: Revenue Share + Reuse Royalties
* Users: $DPCORE rewards for on-chain data contributions
* Data Providers: MCP-standardized access with dynamic pricing

6. **Open Ecosystem Expansion**\
   • Third-party plugin marketplace for MCP-compatible services (cross-chain oracles/compliance tools)\
   • Accelerated scenario innovation through composability

## **III. Competitor Analysis: Technical & Product Capabilities**

| **Dimension**              | **Eliza**                     | **ARC**                                      | **Swarms**                         | **DeepCore**                                                           |
| -------------------------- | ----------------------------- | -------------------------------------------- | ---------------------------------- | ---------------------------------------------------------------------- |
| **Technical Stack**        | Wallet + LLM + Knowledge Base | Multi-Agent Coordination Framework           | Distributed Agent Network          | MCP Protocol + Deep Research Engine                                    |
| **Protocol Standard**      | ✘ Relies on Centralized APIs  | ✘ Custom Communication Protocols             | ✘ No Unified Standards             | ✔ MCP Protocol (Cross-Chain/Cross-Platform)                            |
| **Cross-Chain Support**    | ⚠️ Single-Chain Data Only     | ✘ No Native Cross-Chain Capability           | ⚠️ Requires Plugins                | ✔ Multi-Chain Real-Time Data Access (EVM/Non-EVM)                      |
| **Development Efficiency** | ⚠️ Manual API Integration     | ✘ High Code Complexity                       | ✘ Complex Node Debugging           | ✔ No-Code Toolkit (5x Efficiency Gain)                                 |
| **Data Integration**       | ✘Static Knowledge Base        | ⚠️ Limited Third-Party Sources               | ⚠️ Community-Driven Data           | ✔53+ Integrated Sources (CoinGecko/Dune)                               |
| **Security**               | ⚠️ Basic Access Control       | ✘Centralized Audits                          | ⚠️ Distributed but No Verification | ✔zk-SNARKs On-Chain Verification + Dynamic Policies                    |
| **Key Use Cases**          | Chatbots/NLP Interactions     | Multi-Agent Task Orchestration/AI  App Store | Distributed Computing              | Chatbots/NLP Interactions/Multi-Agent Task Orchestration/AI  App Store |

## **IV. DeepCore's Solutions for Three Core Stakeholders**

| **Target Group**               | **Core Empowerment**                                                                                                               |
| ------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------- |
| **Developers**                 | No-code agent toolkit + decentralized ownership system, eliminating technical barriers and third-party data integration challenges |
| **Users**                      | Composable AI App Store for building scenario-based solutions (e.g., DeFi strategies + social monitoring)                          |
| **Third-party Data Providers** | Standardized MCP protocol integration + dynamic pricing model, reducing technical adaptation costs by 90%                          |

**Three Industry Contradictions Addressed by DeepCore**

1. **Decentralization vs. Centralized Monopoly**: Shatter Big Tech's control over AI capabilities via decentralized agent frameworks;
2. **Data Sovereignty vs. Value Extraction**: On-chain data ownership + contributor revenue sharing (≥n% rewards), enabling fair value redistribution;
3. **Democratization vs. Technical Barriers**: 5x developer efficiency gains with no-code tools, near-zero cost for long-tail innovation.

Built on the high-performance foundation of Solana, DeepCore creates Web3's **"Intelligent Application Factory"** through modular protocol stacks and collaborative networks. Developers can rapidly deploy AI Agents, users can freely combine functionalities, and all participants can share in the growth and value redistribution of the ecosystem.

This transition from **"AI+Chain" to "AI-as-Chain"** delivers scalable, secure and equitable infrastructure, empowering developers to unlock the next wave of blockchain-AI convergence.


# DeepCore MCP protocol

P protocol architecture

DeepCore, as the largest AI Agent application building platform in WEB3, is upgraded to support the MCP protocol to access MCPServer, which provides convenient access to the massive tools of the MCP ecosystem and accelerates the process of building large model applications.

***DeepCore's Core Positioning & Advantages***

*We focus on building **Web3-native solutions** through distributed system architecture and incentive models to create differentiated advantages:*

1. ***Rapid Integration**: Seamlessly connect to MCP services from third-party platforms like CoinMarketCap (CMC) and CoinGecko;*
2. ***Protocol Standardization**: Package DeepCore interfaces as high-availability MCP services for external platform adoption.*

***

## **# MCP Technical Details**

### I. **MCP Technology Overview**

* **Definition**: MCP (Model Context Protocol), proposed by Anthropic in 2024, is an open protocol designed to standardize interactions between AI Agents and external data/tools;
* **Core Value**: Provides a unified interface (USB-C analogy) to eliminate data silos and simplify AI agent-service connectivity;
* **Innovation**: Replaces traditional end-to-end custom encapsulation, becoming the key standard for Web3 AI Agent evolution.

MCP addresses the challenges of AI systems accessing data, replacing traditional fragmented integration approaches with a universal open standard.

### II.**Why DeepCore Bets on MCP Protocol**

<figure><img src="https://1759951032-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvilI5gkHSwBtnpgNfbRd%2Fuploads%2FU0tvEckvjauShjrpH3sP%2Fimage.png?alt=media&amp;token=2ce3b79a-8fa0-4779-8091-75c1697072f7" alt=""><figcaption></figcaption></figure>

**1. Solving Data & Platform Integration Challenges**

* **Industry Pain Points**: Early Web3 AI frameworks(e.g., #AI16Z, #ARC, #Swarms) require custom APIs per data source, leading to plugin bloat and real-time data isolation, They mimicked Web2 giants’ resource monopoly models, relying on superficial narratives like “multi-agent collaboration + Tokenomics” while ignoring Web3-native architecture. True breakthroughs require:
  * **Protocol-layer innovation**: Decentralized data interaction standards beyond Web2-style deployment;
  * **Deep research capabilities**: Enabling AI agents to understand on-chain complexities (e.g., MEV hunting, cross-chain arbitrage).
* **DeepCore Solution**:
  * Reduce **M×N integration complexity** (M clients × N data sources) to **M+N** via MCP protocol;
  * Enable plug-and-play connectivity between AI agents and data sources using JSON-RPC client-server architecture (similar to USB-C adapters);
  * Support dynamic data access, significantly improving efficiency in automation, real-time queries, and cross-platform collaboration.

**2. MCP Advantages in Web3 Environments**

* **Standardized Interfaces**: Directly access on-chain data from Ethereum, Solana, BNB Chain, etc., without custom code (Case: Deep Research MCP server with integrated search engine);
* **Efficiency Leap**: Millisecond-level smart contract state and transaction data queries, adapted to crypto market volatility;
* **Security Architecture**: Built-in authentication and privacy protection mechanisms, compliant with Web3 security standards;
* **Modular Design**: Component reuse reduces maintenance costs and accelerates ecosystem iteration.

**3. Practical Impact**:

| **Legacy Challenges**                          | **MCP Solutions**                                                                        |
| ---------------------------------------------- | ---------------------------------------------------------------------------------------- |
| Custom API required per new data source        | Standardized protocol supports Ethereum, Solana, etc., eliminating redundant development |
| Real-time data isolation (>5min latency)       | On-chain state queries with <500ms latency                                               |
| High security verification cost ($1.2/request) | zk-SNARK verification at <$0.05/request                                                  |

**4. Web3 Advantages**:

* **Cross-chain standardization**: Directly access multi-chain data (e.g., Solana, BNB Chain DeFi positions) without custom code;
* **Dynamic risk response**: Monitor smart contract state changes in real-time to trigger auto-liquidation (case: Uniswap V3 pool attack alerts);
* **Modular reuse**: Developers invoke prebuilt components (e.g., “on-chain sentiment analysis”), boosting efficiency by 70%.

<figure><img src="https://1759951032-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvilI5gkHSwBtnpgNfbRd%2Fuploads%2FAOyWeCMh0e1Rrnf0oUrQ%2Fimage.png?alt=media&amp;token=4fd3a297-9e7f-4d65-b85d-b178d3f6bace" alt=""><figcaption></figcaption></figure>

## **III.The core role of Agent-Core**

1. **Standardized Agent Interaction Protocol**:

**Technical Architecture**

* Employs a **modular API gateway** design with a unified Agent communication interface (DAI-Protocol), supporting multi-protocol adaptation for HTTP/3, WebSocket, and Libp2p
* Integrates **semantic parsing middleware** that automatically converts output formats across AI models (e.g., standardizing responses between GPT-4o, DeepSeek R1 and Claude-3)
* Provides a **compatibility testing toolkit** with 100+ predefined test cases to validate Agent interaction compliance

**Platform Role**

* Enables **cross-chain/cross-platform interoperability**: Agents on Solana can seamlessly interact with DApps on Ethereum, Base, BNB CHAIN... and other ecosystems
* Builds an **open collaboration network**: Developers can modularize Agent functionalities into composable "smart building blocks"
* Use Case: A DeFi strategy Agent automatically fetches Chainlink oracle data while coordinating with a transaction execution Agent on Base

2. **On-Chain/Off-Chain Data Routing Layer (Oracle Hub)**:

**Technical Breakthroughs**

* Innovative **hybrid verification mechanism**: Combines Zero-Knowledge Proofs (zk-SNARKs) with TEE trusted execution environments to ensure data authenticity
* Constructs a **layered data pipeline**:
  * Layer1: Real-time synchronization of on-chain critical data (e.g., token prices, smart contract states)
  * Layer2: Caching of off-chain complex data (social media sentiment, IoT data) via decentralized storage networks
* Develops **dynamic routing algorithms**: Intelligently selects optimal data transmission paths based on network conditions, reducing latency by 40%

**Ecosystem Value**

* Supports **complex application scenarios**:
  * Generative AI Agents access on-chain copyright data in real-time
  * Cross-chain derivatives trading Agents synchronize multi-chain liquidity information
* Enables **data assetization**: Developers can package private data into tradable AI Agents through the data routing layer

3. **Secure Sandbox Execution Environment:**

**Security Architecture**

* Three-tier protection system:
  1. **Hardware-Level Isolation**: Built on Intel SGX trusted execution environments
  2. **Smart Contract Firewall**: Monitors gas consumption patterns in real-time to detect anomalies
  3. **Dynamic Permission Control**: Implements zero-trust architecture requiring re-authorization for each Agent interaction
* Proprietary **Risk Simulation Engine**: Simulates 10,000+ attack scenarios to intelligently generate defense strategies

**Ecosystem Empowerment**

Sparks **new business models**:

* DeFi scenario: AI Agents will validate each other and automatically form strategic alliances, increasing the expected revenue in the Defi domain by 300%.
* Alpha project research and judgment scenario: AI Agent group generates AIization similar to Nansan, Arkham, GMGN and other comprehensive platforms through multiple data platform

Build a self-evolving ecosystem: Collaborative networks will generate knowledge sharing events to drive continuous Agent iteration.


# Deep Research Technology

**Deep Research Agent, Seriously.**

Deep Research is a specialized project research assistant designed for the crypto that generates comprehensive reports on any topic following a workflow similar to OpenAI and Gemini Deep Research. it allows you to customize the models, prompts, report structure, search API, and research depth.

<figure><img src="https://1759951032-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvilI5gkHSwBtnpgNfbRd%2Fuploads%2FbcxCvZL3L8I7nWafnHUP%2Fimage.png?alt=media&amp;token=9ba1ef69-811d-43a2-9391-3fb827f5cc84" alt=""><figcaption></figcaption></figure>

**I. Deep Research: The Intelligent Research Engine for Web3**

Deep Research refers to AI tools' capability to perform complex, multi-step research tasks (e.g., OpenAI Deep Research, Google Gemini Deep Research), featuring:

* **Web crawling & multi-source analysis**: Cross-platform data scraping and structured report generation;
* **Deep reasoning**: Ideal for scenarios requiring long-term tracking and cross-validation (e.g., on-chain behavior pattern analysis).

**Core Value in Web3**:

* **Blockchain data analysis**: Real-time parsing of transaction volume, Gas fee fluctuations, and smart contract interactions to optimize trading strategies;
* **Market trend prediction**: Processing massive datasets to identify price signals and risk alerts (e.g., Perplexity's free tool generating crypto volatility reports);
* **Compliance automation**: Tracking global regulations (e.g., MiCA, FATF guidelines) and outputting audit-ready solutions.

**Technical Breakthrough**:

* **Deep Research MCP servers** (e.g., MCP.so instance) are AI agent-optimized, integrating Gemini multimodal models;
* Enabled by MCP protocol:

  ```
  Research task → MCP data calls → Deep Research analysis → Structured output → On-chain verification  
  ```

***

**II. MultiAgent Architecture & Synergy**

**1. Technical Philosophy**:

* **MultiAgent as inevitability**: DeepCore adopts a "virtual machine + MultiAgent collaboration" architecture, dynamically orchestrating GPT/Claude/DeepSeek model APIs;
* **End-to-end**: From natural language input to executable on-chain solutions (e.g., "Generate and auto-deploy a Uniswap V3 liquidity optimization strategy").

**2. Interaction Revolution**:

* **“Less Structure, More Intelligence”**:
  * Developers create agents via natural language commands (e.g., "Build a BAYC floor price monitoring bot");
  * No-code interface reduces 90% development barriers (testnet data).

**3. MCP + Deep Research Synergy**:

| **Dimension**             | **Legacy Approach**           | **DeepCore Solution**                                               |
| ------------------------- | ----------------------------- | ------------------------------------------------------------------- |
| Task latency              | Minutes (manual intervention) | Seconds (automated workflows)                                       |
| Cross-model collaboration | Manual API bridging           | Protocol-layer auto-routing (e.g., Claude→GPT-4→on-chain execution) |
| Security verification     | Centralized audits            | zk-SNARK on-chain verification + MultiAgent cross-checking          |

<br>


# DeepMatrix AI Agent Store

**DeepMatrix AI Agent Store: Revolutionizing Intelligent Applications in the Web3 Era**

<figure><img src="https://1759951032-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvilI5gkHSwBtnpgNfbRd%2Fuploads%2FAh8KrCXEZB7p7xgwjqte%2Fimage.png?alt=media&amp;token=800fab7f-a129-419c-b7d8-e711dcc62493" alt=""><figcaption></figcaption></figure>

DeepMatrix is DeepCore's **AI Agent application store** for end-users, redefining the paradigm of AI service distribution and utilization. As the "App Store" of the Web3 world, DeepMatrix is not merely a marketplace but an **innovation workshop for intelligent applications** connecting developers and users. Through no-code modular composition, on-chain trust mechanisms, and community-driven ecosystems, it addresses three critical pain points of traditional AI services—**centralized monopolies**, **lack of data sovereignty**, and **imbalanced value distribution**—ushering in a democratized era of "AI as a Service" (AIaaS).

<figure><img src="https://1759951032-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvilI5gkHSwBtnpgNfbRd%2Fuploads%2FZXo3oJcjMhQBlyxJiWpF%2Fimage.png?alt=media&amp;token=416543a8-a9bf-45b7-92f2-07952a78c352" alt=""><figcaption></figcaption></figure>

**Core Architecture & Technological Innovations**

1. **Lego-Style Modular Composition**

**Technical Implementation**

* **Smart Interface Standards**: Define 200+ standardized functional interfaces (e.g., data analysis, on-chain interaction, cross-chain communication) for plug-and-play compatibility
* **Semantic Mapping Engine**: Automatically matches user needs with Agent modules through NLP (e.g. enter “Automatically monitor quality Memecoins and automatically execute trades based on K-techniques” to generate a combination of monitoring and trading Agents)
* **System dynamic recommendation:** based on user behavior data to recommend similarity other high-quality AI Agent

**Industry Revolution**

* **User Autonomy Revolution**: Non-technical users can build complex AI applications without coding, such as:
  * Combining "on-chain monitoring Agent" + "DEX arbitrage Agent" + "risk control Agent" to create a personalized DeFi strategy system within minutes using DeepMatrix AI Agent Store's modular composition tools.
  * Integrating "social media sentiment analysis Agent" with "NFT generation Agent" to automatically mint trending digital collectibles
* **Long-Tail Demand Activation**: Niche scenarios (e.g., specific on-chain data analysis) can be rapidly addressed through modular combinations, unlocking trillion-dollar incremental markets

2. **Community-Driven Reputation System**

**Mechanism Design**

* **One-Dimensional Rating Model**:
  * Economic: User retention rates and profit contribution (We leave the vote entirely in the hands of the market, with end-users participating in multilevel usage evaluations of the AI Agent)
* **Reputation Staking Pool**: Developers must stake $DPCORE tokens to list Agents, with automatic liquidation if negative reviews exceed thresholds

**Ecosystem Impact**

* **Quality Flywheel Effect**: Highly-rated Agents gain traffic priority, incentivizing developers to continuously improve and creating a virtuous cycle
* **Anti-Sybil Attack**: Detects fake reviews through on-chain behavior analysis
* **Value Discovery Mechanism**: There will eventually be a niche AI Agent that receives a million-dollar investment due to high user ratings.

**Revenue Mechanism**

* **Three-Tier Royalty System**:
  1. Base Usage Fee: n$DPCORE per Agent invocation
  2. Composition Revenue Share: Original developers receive 10% when users combine multiple Agents into new solutions
  3. Derivative Creation Rewards: Original IP holders earn 3% from derivative works
* **Liquidity Mining**: Developers staking $DPCORE gain higher store visibility.

**Historical Industry Milestones**

* **Web2 Era**: App Store revolutionized software distribution but charged 30% commissions and monopolized user data
* **Web3 1.0**: DApp stores attempted decentralization but lacked AI integration and user creation capabilities
* **DeepMatrix Paradigm**: Achieves through "composable AI + on-chain economics":
  * Users as both consumers and creators
  * Precise data value redistribution via smart contracts


# DeepCore MCP Store

I**ndustry Milestone: The Birth of Crypto's First MCP Store on DeepCore**

<figure><img src="https://1759951032-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvilI5gkHSwBtnpgNfbRd%2Fuploads%2FKMRqyK566zykUENHBhdV%2Fimage.png?alt=media&amp;token=087d80d1-aa52-484b-8f00-25ba62095d47" alt=""><figcaption></figcaption></figure>

DeepCore's MCP Store is the web3 first service and data trading platform dedicated to the Model Context Protocol (MCP), enabling the publishing of Web3 data and AI Agents as services. Just as Apple's App Store revolutionized mobile ecosystems, MCP Store signifies a paradigm shift in how AI capabilities and on-chain data are created, shared, and commercialized.

DeepCore MCP Store serves as a pioneering platform that enables seamless integration of AI agents with diverse Web3 resources.

This groundbreaking platform allows users to:

* Publish mainstream Web3 market data as MCP services
* Deploy successful AI Agents from DeepCore as monetizable MCP services

***

## **I. Core Innovations**

1. **Pioneering MCP Services**
   * *Web3 Data as MCP Services*: Seamlessly publish and trade mainstream Web3 data streams as standardized MCP modules
   * *AI Agent Monetization*: Deploy successful DeepCore AI Agents as MCP services, enabling developers to earn global royalties
2. **Largest MCP Network**
   * *Discover MCP Servers & Clients*: Access the largest MCP repository, ultimately covering 1,000+ MCP data providers
3. **Token-Driven Economy** *(Planned)*
   * *$DPCORE Integration*:
     * Publish & Earn.
     * Governance & Growth.
   * *Liquidity Mining.*&#x20;

***

## II. DeepCore MCP Store: **Curated MCP Plugins**

The DeepCore MCP Store comes pre-loaded with multiple curated MCP plugins that can be added to your Agent with one-click during creation.

#### **MCP Publishing**

Developers can publish their Agents to MCP Store (using SSE mode), enabling AI assistants like Claude to make real-time calls to DeepCore Agents.

***

## **III. MCP Protocol: STDIO vs SSE**

The MCP protocol supports two distinct communication modes between MCP Servers and Clients:

**STDIO (Standard Input/Output)**

* **"Face-to-face conversation" model**
* Client and server communicate directly through local process stdin/stdout
* Example: During local development, your script launches via command line and exchanges data directly with MCP server without network
* Configuration example (local MongoDB integration):

json复制下载

```
{
  "mcpServers": {
    "mongodb": {
      "command": "npx",
      "args": [
        "-y",
        "@modelcontextprotocol/server-filesystem",
        "~/Downloads"
      ]
    }
  }
}
```

**SSE (Server-Sent Events)**

* **"Hotline call" model**
* Client connects to remote server via HTTP, enabling server push
* Example: AI assistant calling weather API with continuous updates
* Configuration example:

```
{
  "mcpServers": {
    "browser-use-mcp-server": {
      "url": "http://localhost:8000/sse"
    }
  }
}
```

**Key Difference**:\
STDIO requires downloading MCP Server locally, while SSE calls remote-hosted servers via HTTP.\
STDIO provides standardized I/O for seamless program interoperability.

***

#### **MCP Use Cases**

MCP has been adopted in multiple real-world scenarios:

| Case           | Implementation                                            | Benefit                                                      |
| -------------- | --------------------------------------------------------- | ------------------------------------------------------------ |
| **OpenAI**     | Agent SDK supports MCP for external tool integration      | Simplifies multi-step task execution                         |
| **Cursor**     | Enhances software development via API/codebase automation | Streamlines dev workflows                                    |
| **Cloudflare** | Shifts from local to cloud-hosted MCP servers             | Reduces config complexity and improves multi-tenant security |

***

#### **Python Code Example (SSE Client)**

```
import asyncio
from mcp.client.sse import sse_client
from mcp import ClientSession

async def main():
    async with sse_client("https://deepcore.top/mcp/assistant/0bb0d57e-492e-4461cbb40da?api-key=tk_e5d65e604b9a6") as streams:
        async with ClientSession(*streams) as session:
            await session.initialize()
            
            # List available tools
            print(await session.list_tools())
            
            # Call specific tool
            response = await session.call_tool('Dexranking', {'message': 'hello world'})
            print(response)

if __name__ == '__main__':
    asyncio.run(main())
```

## **IV. Why MCP Store is Revolutionary?**

* *First-Mover Advantage*: The only platform transforming Web3 data and AI Agents into tradable, composable assets
* *Data Superiority*: Building the most comprehensive MCP marketplace covering Web3 data services (including valuable Web2 data)

***

**The "App Store" for Web3 AI**\
Just as App Store propelled mobile apps into a trillion-dollar economy, MCP Store aims to become the liquidity hub for Web3 AI's future:

* *For Data Providers*: Rapidly deploy and monetize AI models as MCP services
* *For Developers*: Integrate battle-tested MCP services into workflows

| Feature                 | Description                                                                                                         |
| ----------------------- | ------------------------------------------------------------------------------------------------------------------- |
| WEB3 Data Publishing    | Enables publishing mainstream WEB3 market data as MCP services, providing real-time cryptocurrency insights.        |
| AI Agent Deployment     | Allows deployment of successful AI Agents from DeepCore as monetizable MCP services.                                |
| Token Economics         | Integrated with $*DPCORE* token economics, featuring governance and reward mechanisms to incentivize participation. |
| Server/Client Network   | The largest collection of crypto MCP servers for developers to discover and utilize.                                |
| User-Friendly Interface | App Store-like intuitive interface for service management and deployment.                                           |


# Developer Toolkit Suite

With this set of tools, DeepCore is building a GitHub-style collaborative ecosystem for AI development, enabling everyone with a creative idea to become an architect in the age of Web3 intelligence.

<figure><img src="https://1759951032-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvilI5gkHSwBtnpgNfbRd%2Fuploads%2FxUiHPgq24oy0lkgBI9PR%2Fimage.png?alt=media&amp;token=cc7a85dd-941d-4642-8559-3ef31e78ab21" alt=""><figcaption></figcaption></figure>

## **Technical Implementation**

1. **Visual Orchestrator (Drag-n-Drop UI)**

* **Architecture**: Built on React-Flow with 200+ predefined logic modules (data fetching, smart contract calls, ML inference), enabling complex workflow design via graphical connections.
* **Dynamic Code Generation**: Converts drag-and-drop actions into Solidity/Python code in real-time, with automated gas optimization (27% average reduction).

**Pre-Trained Model Library**

* **Model Ecosystem**: Integrates Hugging Face, OpenAI, and Solana specific models, covering 20+ vertical scenarios like DeFi arbitrage strategies and DEX metadata generation.
* **Federated Learning Support**: Developers can fine-tune models with private data, with training processes verified via zkML (Zero-Knowledge Machine Learning).

**Debugging Simulator**

* **Multi-Chain Sandbox**: with real-time gas analysis and state snapshot rollback.
* **AI-Powered Diagnostics**: Leverages GPT-4 code interpreter to identify error sources and provide fixes (92% accuracy).

2. **IM Integration SDK**

* **Atomic Interaction Protocol**: Encapsulates Telegram Bot API and Discord Slash Commands to atomically bind message flows with on-chain operations.
* **Intent Recognition Engine**: Converts natural language commands into smart contract calls via NLP (e.g., "Send 100 USDT to Alice" auto-generates ERC-20 interaction code).

**Industry Paradigm Shift**

**Democratized Development**

* **Creator Economy Rise**: 41% of new Agents are from non-technical creators, including artists, traders, and community managers.
* **Knowledge Sharing Revolution**: Debugging the simulator's error database accumulates solutions to form a decentralized knowledge graph.

**Interaction Refactoring**

Conversation as a Service (CaaS): Users perform complex operations through natural language commands.

Chained Behavior Visualization: Drag-and-drop process design makes smart contract logic intuitively understandable to users, driving Web3 mass adoption.

<br>


# TokenForge Launchpad (Plan)

**TokenForge Launchpad: AI Agent Tokenization Engine**

\
**TokenForge Launchpad** is a core module of the **DeepCore** platform, offering developers a one-stop tokenization solution. It enables developers to rapidly issue customized tokens based on their AI Agent's functionalities and business logic, achieving **AI capability tokenization**, **on-chain revenue models**, and **automated community governance**. By natively integrating with the DeepWeb3 protocol layer and BNB Chain ecosystem, developers can complete the entire process—from token design to liquidity deployment—in under 5 minutes.

**Core Features**

1. **AI-Driven Token Template Library**
   * **Scenario-Specific Templates**: 20+ prebuilt token models, including:
     * *Utility Token* (e.g., payment tokens for AI service access)
     * *Governance Token* (tokenized Agent control rights)
     * *Revenue Share Token* (profit-sharing tokens for Agent usage)
   * **Dynamic Parameter Configuration**: AI analyzes Agent usage data to recommend key parameters (total supply, emission curves) with 89% accuracy.
2. **Economic Model Sandbox**
   * **Revenue Simulator**: Predicts token performance under various scenarios (staking APY, liquidity pool yields).
   * **Compliance Check**: Auto-adapts to BEP-20 standards and verifies regulatory compliance for target jurisdictions.
3. **Cross-Chain Issuance Protocol**
   * **Solana  First Deployment**: Natively supports Solana standard while enabling one-click deployment across Solana and EVM-compatible chains (e.g., ETH, BSC, BASE).
   * **HIVE Multi-Chain Sync**: Automatically synchronizes multi-chain token states via Solana BlockChain's Oracle Hub (latency <500ms).
4. **Liquidity Accelerator**
   * **Solana  Ecosystem Integration**: Deeply integrates with native DEXs for automated liquidity pool creation.
   * **Dynamic Market-Making**: Adjusts trading fees based on Solana gas price fluctuations, boosting liquidity provider yields by 22%.

***

**Token Issuance & Revenue Execution Flow**

**Step 1: Token Creation**

1. Developers define token attributes via a visual panel:
   * Select template type (Utility/Governance/Revenue Share).
   * Configure token symbol, total supply, and allocation ratios (team/ecosystem fund/community).
   * Bind AI Agent permissions (e.g., token holders unlock premium API access).

**Step 2: Smart Contract Deployment**

* Deploys audited token contracts using **Agent-Core Protocol Layer**'s secure sandbox.
* Supports advanced token mechanics:
  * *Staking Mining*: Users earn $DPC governance tokens by staking assets.
  * *Burn Mechanism*: 1% of AI service fees permanently destroy tokens.

**Step 3: Revenue Model Binding**

* **Automated Royalties**: Token holders share Agent usage fees proportionally (linked to DeepMatrix Store’s royalty system).
* **Governance Monetization**: Governance token holders vote on Agent upgrades, earning $WEB3 fuel tokens for approved proposals.

**Step 4: Liquidity Activation**

* Deploys liquidity pools on target DEXs via **cross-chain routing protocols**.
* Initial liquidity (15% of token supply) is auto-locked, with remaining tokens released through community mining.

***

**Unified Revenue Architecture**

| Revenue Source          | Distribution Mechanism                  | Linked Module               |
| ----------------------- | --------------------------------------- | --------------------------- |
| Agent Service Fees      | 50% to holders, 30% burned, 20% to devs | DeepMatrix Royalty System   |
| Governance Rewards      | 100-500 $DCI per approved proposal      | Ecosystem Governance        |
| Liquidity Mining Yields | 15-45% APY in $DCI for staking          | Developer Incentive Program |
| Cross-Chain Fee Sharing | 3% of cross-chain fees to holders       | HIVE Collaboration Network  |

***

**Use Case**

**Case: AlphaBot Strategy Token ($DCI)**

* **Background**: A quantitative team develops DeFi Arbitrage Agent.
* **Tokenization Process**:
  1. Issued 10M $DCI (Revenue Share type) via TokenForge.
  2. Token benefits:
     * 15% of daily Agent profits distributed to holders.
     * Staked $DCI prioritizes access to advanced strategies.
  3. Launched liquidity on DEX.

***

**Technical Integration**

* **Security Foundation**: Token contracts undergo **formal verification** in Agent-Core’s sandbox, blocking 98% of vulnerabilities.
* **Cross-Chain Interoperability**: Uses Oracle Hub for sub-500ms multi-chain state sync.
* **Compliance Engine**: Auto-generates KYC/AML reports compliant with 12 jurisdictions (Singapore, Switzerland, etc.).

***

By integrating **TokenForge Launchpad**, DeepCore merges AI Agent value capture with token economics, pioneering the **AI-as-Asset** paradigm where every intelligent Agent evolves into a self-sustaining economic ecosystem.<br>


# Technical Architecture

{% embed url="<https://github.com/0xdevpro/deepcore>" %}

DeepCore is built on the innovative MCP (Model-Controller-Protocol) architecture, a design pattern that enables us to build highly flexible and powerful intelligent agent systems.

<figure><img src="https://1759951032-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvilI5gkHSwBtnpgNfbRd%2Fuploads%2FDxxiJTDgjb8ScBrRTENJ%2Fimage.png?alt=media&amp;token=ba59139c-d1ad-4c9a-9611-da98349adeaa" alt=""><figcaption></figcaption></figure>

DeepCore's architecture consists of three main layers:

#### 1. Web3 Agent Store Layer

The top layer provides a marketplace of specialized agents for different purposes:

* **Analysis Agent** - For data analytics and insights generation
* **Trade Agent** - For executing trading strategies on various platforms
* **Media Agent** - For content creation and media interaction
* **DeepResearch Agent** - For in-depth research and knowledge discovery
* **Additional specialized agents** - Extensible for various domain-specific tasks

#### 2. DeepCore Agent Protocol Layer

The core protocol layer is where the main agent intelligence and orchestration happens:

**Service Components**

* **MCP Service** - Implements the Model-Controller-Protocol pattern
* **SSE (Server-Sent Events)** - Provides real-time communication
* **CMD** - Command interface for agent control
* **HTTP Service** - RESTful API endpoints for integrations
* **OpenAPIs** - Standardized API interfaces for external connectivity
* **SDKs** - Software Development Kits for various programming languages

**Agent Orchestration**

* **Planner Agent** - Central coordinator that breaks down complex tasks
* **TaskAgents** - Specialized agents that execute specific subtasks
* **Tools Integration** - Various tool categories available to agents:
  * **CodeAct** - For code generation and execution
  * **Browser** - For web browsing and information retrieval
  * **Initial Tools** - Basic built-in tooling
  * **Search** - Search capabilities across various sources
  * **Custom Tools** - User-defined or domain-specific tools

**Client Integration**

* **Tools Center** - Central registry for tool discovery and management
* **Authorization** - Security and permissions management
* **MCP Service for Client** - Client-facing interfaces for various platforms (APP | WEB | Desktop)

#### 3. Chain Foundation Layer

The bottom layer provides blockchain and data infrastructure:

* **Multi-chain Support** - Integration with major blockchains (BASE, BTC, ETH, BNB, SOL, APT, SUI, etc.)
* **Social Media Integration** - Connections to platforms like X and Telegram
* **DeFi Integration** - Support for DEX and CEX interactions
* **Third-party Platform Support** - Extensible integration with external platforms

#### Core Components

**Agent System**

DeepCore's agent system consists of the following main components:

* **Agent Core** - Core agent logic implementation, managing reasoning processes and tool invocation
* **Memory System** - Short-term and long-term memory management, supporting context awareness and historical queries
* **Tool Manager** - Tool registration, validation, and execution management
* **Prompt Engine** - Advanced prompt templates and prompt optimization
* **LLM Connector** - Multi-model interface, supporting model mixing and fallback strategies

**Tool Integration**

DeepCore supports multiple tool types:

* **OpenAPI Tools** - Automatically integrate RESTful APIs through OpenAPI specifications
* **Blockchain Tools** - Specialized tools for interacting with various blockchain networks
* **Data Analysis Tools** - Tools for processing and analyzing large amounts of data
* **Custom Tools** - Support for developers to create and register custom tools

**Security Mechanisms**

DeepCore implements multi-layered security mechanisms:

* **Permission Control** - Fine-grained API access permission management
* **Resource Limits** - Monitoring and limiting agent resource usage
* **Audit Logs** - Comprehensive operation logging
* **Vulnerability Protection** - Mechanisms to prevent common security vulnerabilities


# Quick Start Guide

### 🚀 Your First Agent in 5 Minutes

Welcome to DeepCore! This guide will help you create your first AI agent in just a few minutes. Let's get started!

#### Prerequisites

Before you begin, make sure you have:

* `Python 3.11+`
* `pip or poetry`
* `Basic understanding of Python`
* `An API key for your preferred AI model (e.g., OpenAI, Claude)`

#### Installation

{% code overflow="wrap" %}

```
# Using pip
pip install deepcore
​
# Or using poetry
poetry add deepcore
```

{% endcode %}

#### 1. Create Your First Agent

```
from deepcore import Agent
​
# Initialize a simple agent
agent = Agent(
    name="my_first_agent",
    description="A helpful assistant",
    model="gpt-4"  # or any other supported model
)
​
# Start a conversation
response = agent.chat("Hello! Can you help me with some data analysis?")
print(response)
```

#### 2. Add Tools to Your Agent

```
from deepcore.tools import Calculator, WebSearch
​
# Create an agent with tools
agent = Agent(
    name="powered_agent",
    description="An agent that can calculate and search",
    model="gpt-4",
    tools=[Calculator(), WebSearch()]
)
​
# Ask the agent to use tools
response = agent.chat("What is the square root of 144 plus the current temperature in New York?")
print(response)
```

#### 3. Create a Custom Tool

```
from deepcore.tools import BaseTool
​
class WeatherTool(BaseTool):
    def __init__(self):
        super().__init__(
            name="weather",
            description="Get weather information"
        )
    
    async def _run(self, location: str) -> str:
        # Implement weather checking logic
        return f"Weather information for {location}"
​
# Use your custom tool
agent = Agent(
    name="weather_agent",
    tools=[WeatherTool()]
)
```

#### 4. Multi-Agent Collaboration

```
from deepcore import Agent, Team
​
# Create specialized agents
researcher = Agent(name="researcher", tools=["web_search"])
analyst = Agent(name="analyst", tools=["calculator"])
writer = Agent(name="writer", tools=["text_processor"])
​
# Create a team
team = Team(
    name="research_team",
    agents=[researcher, analyst, writer]
)
​
# Let the team work together
result = team.collaborate("Research the impact of AI on healthcare and prepare a report")
```

#### 5. Deploy Your Agent

```
from deepcore.deploy import APIServer
​
# Create an API server
server = APIServer(agents=[agent])
​
# Start the server
server.run(host="localhost", port=8000)
```

Now your agent is accessible via REST API:

```
curl -X POST http://localhost:8000/chat \
    -H "Content-Type: application/json" \
    -d '{"message": "Hello, agent!"}'
```

### Next Steps

#### Explore More Features

* Add memory to your agents
* Implement custom workflows
* Create agent teams
* Add authentication
* Monitor performance

#### Advanced Topics

* Custom model integration
* Advanced tool development
* Multi-agent orchestration
* Performance optimization
* Security implementation

#### Best Practices

1. Always handle errors gracefully
2. Monitor agent performance
3. Implement rate limiting
4. Secure sensitive information
5. Test thoroughly

### Common Use Cases

#### Customer Service

```
service_agent = Agent(
    name="customer_service",
    description="Helpful customer service agent",
    tools=["faq", "ticket_system", "email"]
)
```

#### Data Analysis

```
analysis_agent = Agent(
    name="data_analyst",
    description="Data analysis specialist",
    tools=["pandas", "matplotlib", "database"]
)
```

#### Content Creation

```
content_agent = Agent(
    name="content_creator",
    description="Creative content writer",
    tools=["text_generator", "image_creator"]
)
```

### Troubleshooting

#### Common Issues

1. Model API Issues

```
# Implement fallback
agent = Agent(
    name="reliable_agent",
    model="gpt-4",
    fallback_model="gpt-3.5-turbo"
)
```

2. Rate Limiting

```
# Implement rate limiting
agent = Agent(
    name="controlled_agent",
    rate_limit=10,  # requests per minute
    rate_limit_period=60
)
```

3. Memory Issues

```
# Manage memory
agent = Agent(
    name="memory_efficient",
    max_memory_tokens=1000,
    memory_type="sliding_window"
)
```


# Development Guide

Development Environment Setup

#### Prerequisites

* Python 3.11+
* Poetry for dependency management
* Docker (optional)
* Git

<figure><img src="https://1759951032-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvilI5gkHSwBtnpgNfbRd%2Fuploads%2FRiuQ4XwiaIg3AF9JIgey%2Fimage.png?alt=media&amp;token=a6148519-4d39-4514-a435-4263264bd6c8" alt=""><figcaption></figcaption></figure>

#### Local Development Setup

1. Clone the repository:

```
git clone https://github.com/0xdevpro/deepcore.git
cd deepcore
```

2. Install dependencies:

```
poetry install
```

3. Set up environment variables:

```
cp .env.example .env
```

4. Configure your `.env` file:

```
HOST=localhost
PORT=8000
DEBUG=true
JWT_SECRET=your_jwt_secret
DATABASE_URL=postgresql://user:password@localhost:5432/deepcore
```

5. Start the development server:

```
poetry run python api.py
```

### Project Structure

```
deepcore/
├── agents/
│   ├── agent/          # Core agent implementation
│   ├── api/            # API endpoints
│   ├── common/         # Shared utilities
│   ├── middleware/     # Middleware components
│   ├── models/         # Data models
│   ├── protocol/       # Protocol definitions
│   ├── services/       # Business logic
│   └── utils/          # Utility functions
├── sql/                # Database migrations
├── tests/              # Test suite
├── api.py             # Main application entry
├── pyproject.toml     # Project dependencies
└── README.md          # Project documentation
```

### Core Components

#### Agent System

The agent system is the heart of DeepCore. It consists of several key components:

1. **Agent Core**

```
from agents.agent.base import BaseAgent
​
class CustomAgent(BaseAgent):
    def __init__(self, config: dict):
        super().__init__(config)
        self.tools = []
        self.memory = []
​
    async def process(self, input_data: str) -> str:
        # Implement agent processing logic
        response = await self._think(input_data)
        return response
​
    async def _think(self, input_data: str) -> str:
        # Implement thinking logic
        pass
```

2. **Tool Integration**

```
from agents.agent.tool import BaseTool
​
class CustomTool(BaseTool):
    def __init__(self):
        super().__init__(
            name="custom_tool",
            description="Tool description"
        )
​
    async def _run(self, input_data: dict) -> dict:
        # Implement tool logic
        result = await self.process_data(input_data)
        return {"result": result}
​
    async def process_data(self, data: dict) -> str:
        # Implement specific data processing
        pass
```

#### API Layer

The API layer is built using FastAPI:

```
from fastapi import APIRouter, Depends
from agents.services.agent_service import AgentService

router = APIRouter()

@router.post("/agent/create")
async def create_agent(
    data: AgentCreate,
    service: AgentService = Depends()
):
    return await service.create_agent(data)

@router.get("/agent/{agent_id}")
async def get_agent(
    agent_id: str,
    service: AgentService = Depends()
):
    return await service.get_agent(agent_id)
```

#### Service Layer

Services handle business logic:

```
from agents.models.db import AgentModel
from agents.protocol.schemas import AgentCreate

class AgentService:
    async def create_agent(self, data: AgentCreate) -> AgentModel:
        # Validate data
        self._validate_agent_data(data)
        
        # Create agent
        agent = await AgentModel.create(**data.dict())
        
        # Initialize tools
        await self._initialize_tools(agent)
        
        return agent

    async def _initialize_tools(self, agent: AgentModel):
        # Tool initialization logic
        pass
```

### Development Guidelines

#### Code Style

1. Follow PEP 8 guidelines
2. Use type hints
3. Document functions and classes
4. Write meaningful commit messages

Example:

```
from typing import Optional, List

class DataProcessor:
    """
    Processes data for agent consumption.
    
    Attributes:
        batch_size: Size of data batches to process
        max_items: Maximum number of items to process
    """
    
    def __init__(self, batch_size: int = 100, max_items: Optional[int] = None):
        self.batch_size = batch_size
        self.max_items = max_items
    
    def process_batch(self, items: List[dict]) -> List[dict]:
        """
        Process a batch of items.
        
        Args:
            items: List of items to process
            
        Returns:
            List of processed items
        """
        return [self._process_item(item) for item in items]
```

#### Testing

1. Write unit tests for all components
2. Use pytest for testing
3. Maintain high test coverage

Example:

```
import pytest
from agents.services.agent_service import AgentService

@pytest.fixture
def agent_service():
    return AgentService()

@pytest.mark.asyncio
async def test_agent_creation(agent_service):
    data = AgentCreate(
        name="test_agent",
        description="Test agent",
        mode="ReAct"
    )
    
    agent = await agent_service.create_agent(data)
    assert agent.name == "test_agent"
    assert agent.mode == "ReAct"
```

#### Error Handling

Implement proper error handling:

```
from agents.exceptions import AgentError

class AgentService:
    async def create_agent(self, data: AgentCreate) -> AgentModel:
        try:
            # Attempt to create agent
            agent = await AgentModel.create(**data.dict())
            return agent
        except Exception as e:
            raise AgentError(f"Failed to create agent: {str(e)}")
```

### Database Management

#### Migrations

Use Alembic for database migrations:

```
# Create a new migration
alembic revision --autogenerate -m "Add agent table"

# Run migrations
alembic upgrade head
```

#### Models

Define SQLAlchemy models:

```
from sqlalchemy import Column, String, Integer
from agents.models.base import Base

class Agent(Base):
    __tablename__ = "agents"
    
    id = Column(String, primary_key=True)
    name = Column(String, nullable=False)
    description = Column(String)
    mode = Column(String, nullable=False)
```

### Deployment

#### Docker Deployment

1. Build the image:

```
docker build -t deepcore .
```

2. Run the container:

```
docker run -p 8000:8000 \
    -e DATABASE_URL=postgresql://user:password@host:5432/deepcore \
    -e JWT_SECRET=your_secret \
    deepcore
```

#### Production Considerations

1. Use proper logging:

```
import logging

logger = logging.getLogger(__name__)

class AgentService:
    async def create_agent(self, data: AgentCreate):
        logger.info(f"Creating agent: {data.name}")
        try:
            agent = await AgentModel.create(**data.dict())
            logger.info(f"Agent created successfully: {agent.id}")
            return agent
        except Exception as e:
            logger.error(f"Failed to create agent: {str(e)}")
            raise
```

2. Implement monitoring:

```
from prometheus_client import Counter, Histogram

request_count = Counter(
    'agent_requests_total',
    'Total agent requests'
)

request_latency = Histogram(
    'agent_request_latency_seconds',
    'Agent request latency'
)
```

### Contributing

1. Fork the repository
2. Create a feature branch
3. Write tests
4. Submit a pull request

#### Pull Request Guidelines

* Follow the code style guide
* Include tests
* Update documentation
* Add changelog entry

### Troubleshooting

#### Common Issues

1. Database Connection Issues:

```
try:
    await database.connect()
except Exception as e:
    logger.error(f"Database connection failed: {str(e)}")
    sys.exit(1)
```

2. Authentication Problems:

```
if token_error:
    logger.warning(f"Authentication failed for user: {user_id}")
    raise AuthenticationError("Invalid token")
```

#### Debugging

Enable debug logging:

```
import logging

logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)

logger.debug("Detailed debugging information")
```

### Performance Optimization

1. Use connection pooling:

```
from databases import Database

database = Database(
    DATABASE_URL,
    min_size=5,
    max_size=20
)
```

2. Implement caching:

```
from fastapi_cache import FastAPICache
from fastapi_cache.backends.redis import RedisBackend

@router.get("/agent/{agent_id}")
@cache(expire=60)
async def get_agent(agent_id: str):
    return await agent_service.get_agent(agent_id)
```

### Security Best Practices

1. Input validation:

```
from pydantic import BaseModel, validator

class UserInput(BaseModel):
    name: str
    email: str
    
    @validator('email')
    def validate_email(cls, v):
        if not '@' in v:
            raise ValueError('Invalid email')
        return v
```

2. Rate limiting:

```
from fastapi import Depends
from agents.middleware.rate_limit import rate_limit
​
@router.post("/agent/create")
@rate_limit(max_requests=10, window_seconds=60)
async def create_agent(data: AgentCreate):
    return await agent_service.create_agent(data)
```


# DeepCore API

DeepCore API Documentation

## Overview

DeepCore API is a powerful set of RESTful API interfaces that provide the ability to interact with the DeepCore platform. These interfaces allow developers to create and manage agents, models, files, tools, prompts, categories, and other resources.

### Base URL

All API requests are based on the following base URL:

```
https://api.deepcore.top
```

### Authentication

DeepCore API uses API Token authentication, which is simple to implement and suitable for both development and production environments.

#### API Token Authentication

API Token is a long-term authentication credential used to access DeepCore APIs. It simplifies the authentication process and is recommended for all integration scenarios.

**Obtaining an API Token**

You can obtain an API Token from one of the following sources:

1. **DeepCore Official Website**: Log in to [deepcore.top](https://deepcore.top/) and navigate to your profile settings to find your API Token.
2. **API Token Endpoint**: If you already have account credentials, you can use the following endpoint to obtain an API Token:

```
POST /api/open/token
```

**Using API Token**

After obtaining an API Token, include it in the `X-API-Token` request header for all API calls:

```
import requests
​
# Use API Token to call interfaces
headers = {"X-API-Token": "tk_your_api_token"}  # Replace with your API Token
​
# For example, get the list of agents
response = requests.get(
    "https://api.deepcore.top/api/agents",
    headers=headers
)
​
print(response.json())
```

**API Token Format**

API Tokens follow a specific format: `tk_` followed by a 20-character string. For example:

```
tk_a1b2c3d4e5f6g7h8i9j0
```

**Resetting API Token**

If your API Token is compromised or you need to reset it for security reasons, you can use the reset endpoint:

```
POST /api/open/token/reset
```

Note: Resetting your API Token will invalidate the previous token.

### Open Dialogue API

The Open Dialogue API is a mechanism provided by DeepCore that allows third-party applications to integrate agent dialogue functionality in a simplified way.

#### Interface Definition

```
POST /api/open/agents/{agent_id}/dialogue
```

#### Authentication Method

Uses API Token authentication via the `X-API-Token` request header.

#### Request Parameters

| Parameter         | Type   | Required | Description                                                                                                                                                              |
| ----------------- | ------ | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `message`         | string | Yes      | User message content                                                                                                                                                     |
| `conversation_id` | string | No       | Conversation ID, used to continue an existing conversation. Developers are recommended to define and pass their own conversation ID for tracking and management purposes |

#### Example Request

```
# Use API Token for dialogue (supports streaming response)
curl -X POST https://api.deepcore.top/api/open/agents/your_agent_id/dialogue \
  -H "Content-Type: application/json" \
  -H "X-API-Token: tk_your_api_token" \
  -d '{
    "message": "Hello, please introduce yourself",
    "conversation_id": "your-custom-conversation-id"
  }'
​
# Response will be returned in Server-Sent Events format
```

#### Response Format

The interface returns Server-Sent Events (SSE) format streaming responses. Each event is prefixed with `event:` and `data:`, and comes in two main types:

1. **Status events**: Indicate the current status of the request processing
2. **Message events**: Contain actual response content, usually in small chunks

**Example Response**

```
event: status
data: {"message": "task understanding"}
​
event: status
data: {"message": "generate response"}
​
event: message
data: {"type": "markdown", "text": "H"}
​
event: message
data: {"type": "markdown", "text": "e"}
​
event: message
data: {"type": "markdown", "text": "l"}
​
event: message
data: {"type": "markdown", "text": "l"}
​
event: message
data: {"type": "markdown", "text": "o"}
​
event: message
data: {"type": "markdown", "text": "!"}
​
event: message
data: {"type": "markdown", "text": " "}
​
event: message
data: {"type": "markdown", "text": "H"}
​
event: message
data: {"type": "markdown", "text": "o"}
​
event: message
data: {"type": "markdown", "text": "w"}
​
event: message
data: {"type": "markdown", "text": " "}
​
event: message
data: {"type": "markdown", "text": "c"}
​
event: message
data: {"type": "markdown", "text": "a"}
​
event: message
data: {"type": "markdown", "text": "n"}
​
event: message
data: {"type": "markdown", "text": " "}
​
event: message
data: {"type": "markdown", "text": "I"}
​
event: message
data: {"type": "markdown", "text": " "}
​
event: message
data: {"type": "markdown", "text": "a"}
​
event: message
data: {"type": "markdown", "text": "s"}
​
event: message
data: {"type": "markdown", "text": "s"}
​
event: message
data: {"type": "markdown", "text": "i"}
​
event: message
data: {"type": "markdown", "text": "s"}
​
event: message
data: {"type": "markdown", "text": "t"}
​
event: message
data: {"type": "markdown", "text": " "}
​
event: message
data: {"type": "markdown", "text": "you today?"}
```

#### Usage Example (Python)

```
import requests
​
# Using API Token
token = "tk_your_api_token"
agent_id = "your_agent_id"
​
# Send request and handle streaming response
response = requests.post(
    f"https://api.deepcore.top/api/open/agents/{agent_id}/dialogue",
    headers={
        "X-API-Token": token
    },
    json={
        "message": "Hello, please introduce yourself",
        "conversation_id": "your-custom-conversation-id"  # Custom conversation ID
    },
    stream=True  # Enable streaming
)
​
# Handle streaming response
for chunk in response.iter_lines():
    if chunk:
        data = chunk.decode('utf-8')
        if data.startswith('data: '):
            # Remove 'data: ' prefix
            content = data[6:]
            print(content)
```

#### Usage Example (JavaScript)

```
// Using API Token for dialogue
const token = "tk_your_api_token";
const agentId = "your_agent_id";
​
fetch(`https://api.deepcore.top/api/open/agents/${agentId}/dialogue`, {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'X-API-Token': token
  },
  body: JSON.stringify({
    message: "Hello, please introduce yourself",
    conversation_id: "your-custom-conversation-id"  // Custom conversation ID
  })
})
.then(response => {
  // Create stream reader
  const reader = response.body.getReader();
  const decoder = new TextDecoder();
  let buffer = '';
  
  function read() {
    return reader.read().then(({ done, value }) => {
      if (done) return;
      
      // Decode received data
      const chunk = decoder.decode(value, { stream: true });
      buffer += chunk;
      
      // Process complete lines
      const lines = buffer.split('\n');
      buffer = lines.pop(); // Keep the last potentially incomplete line
      
      // Process each line of data
      for (const line of lines) {
        if (line.startsWith('data: ')) {
          // Remove 'data: ' prefix
          const content = line.substring(6);
          console.log(content);
        }
      }
      
      // Continue reading
      return read();
    });
  }
  
  return read();
})
.catch(error => {
  console.error('Dialogue error:', error);
});
```

### API Routes

#### Authentication API

| Path                    | Method | Description     |
| ----------------------- | ------ | --------------- |
| `/api/open/token`       | POST   | Get API Token   |
| `/api/open/token/reset` | POST   | Reset API Token |

#### Agent API

| Path                          | Method | Description                |
| ----------------------------- | ------ | -------------------------- |
| `/api/agents`                 | GET    | Get list of all agents     |
| `/api/agents`                 | POST   | Create new agent           |
| `/api/agents/{agent_id}`      | GET    | Get specific agent details |
| `/api/agents/{agent_id}`      | PUT    | Update specific agent      |
| `/api/agents/{agent_id}`      | DELETE | Delete specific agent      |
| `/api/agents/{agent_id}/chat` | POST   | Chat with an agent         |

#### Open Dialogue API

| Path                                   | Method | Description                                                 |
| -------------------------------------- | ------ | ----------------------------------------------------------- |
| `/api/open/agents/{agent_id}/dialogue` | POST   | Open agent dialogue interface, supports streaming responses |
| `/api/open/examples`                   | GET    | Get API usage example code                                  |

#### Model API

| Path                     | Method | Description                |
| ------------------------ | ------ | -------------------------- |
| `/api/models`            | GET    | Get list of all models     |
| `/api/models`            | POST   | Add new model              |
| `/api/models/{model_id}` | GET    | Get specific model details |
| `/api/models/{model_id}` | PUT    | Update specific model      |
| `/api/models/{model_id}` | DELETE | Delete specific model      |

#### File API

| Path                            | Method | Description               |
| ------------------------------- | ------ | ------------------------- |
| `/api/files`                    | GET    | Get list of all files     |
| `/api/files`                    | POST   | Upload new file           |
| `/api/files/{file_id}`          | GET    | Get specific file details |
| `/api/files/{file_id}`          | DELETE | Delete specific file      |
| `/api/files/{file_id}/download` | GET    | Download specific file    |

#### Tool API

| Path                   | Method | Description               |
| ---------------------- | ------ | ------------------------- |
| `/api/tools`           | GET    | Get list of all tools     |
| `/api/tools`           | POST   | Create new tool           |
| `/api/tools/{tool_id}` | GET    | Get specific tool details |
| `/api/tools/{tool_id}` | PUT    | Update specific tool      |
| `/api/tools/{tool_id}` | DELETE | Delete specific tool      |

#### Prompt API

| Path                       | Method | Description                 |
| -------------------------- | ------ | --------------------------- |
| `/api/prompts`             | GET    | Get list of all prompts     |
| `/api/prompts`             | POST   | Create new prompt           |
| `/api/prompts/{prompt_id}` | GET    | Get specific prompt details |
| `/api/prompts/{prompt_id}` | PUT    | Update specific prompt      |
| `/api/prompts/{prompt_id}` | DELETE | Delete specific prompt      |

#### Category API

| Path                            | Method | Description                   |
| ------------------------------- | ------ | ----------------------------- |
| `/api/categories`               | GET    | Get list of all categories    |
| `/api/categories`               | POST   | Create new category           |
| `/api/categories/{category_id}` | GET    | Get specific category details |
| `/api/categories/{category_id}` | PUT    | Update specific category      |
| `/api/categories/{category_id}` | DELETE | Delete specific category      |

#### Image API

| Path                  | Method | Description                  |
| --------------------- | ------ | ---------------------------- |
| `/api/images`         | POST   | Generate image               |
| `/api/images/history` | GET    | Get image generation history |

#### Open API

| Path               | Method | Description                            |
| ------------------ | ------ | -------------------------------------- |
| `/api/open/chat`   | POST   | Open chat interface                    |
| `/api/open/agents` | GET    | Get list of publicly accessible agents |

#### MCP API

| Path                            | Method   | Description                            |
| ------------------------------- | -------- | -------------------------------------- |
| `/api/mcp/create`               | POST     | Create new MCP server                  |
| `/api/mcp/list`                 | GET      | List all MCP servers                   |
| `/api/mcp/{mcp_name}`           | DELETE   | Delete specified MCP server            |
| `/api/mcp/{mcp_name}/prompts`   | POST     | Add prompt template to MCP server      |
| `/api/mcp/{mcp_name}/resources` | POST     | Add resource to MCP server             |
| `/api/mcp/tools/{tool_id}`      | GET      | Get MCP service information for a tool |
| `/mcp/{mcp_name}`               | GET/POST | MCP server endpoint                    |

### Error Handling

All API responses follow a unified format:

```
{
  "code": 0,        // Error code, 0 indicates success
  "msg": "Success", // Error message
  "data": {}        // Response data
}
```

#### Common Error Codes

| Error Code | Description                  |
| ---------- | ---------------------------- |
| 0          | Success                      |
| 10001      | Invalid token                |
| 10002      | Token expired                |
| 10003      | Invalid username or password |
| 10004      | User not found               |
| 20001      | Resource doesn't exist       |
| 20002      | Resource already exists      |
| 30001      | Parameter error              |
| 40001      | API call error               |
| 50001      | Internal server error        |

### Example Requests

#### Using API Token to Call Interfaces

```
curl -X GET https://api.deepcore.top/api/agents \
  -H "X-API-Token: tk_your_api_token"
```

### Integration and Usage

DeepCore API can be integrated with various programming languages and frameworks, including Python, JavaScript, Java, etc. Requests can be initiated through HTTP client libraries or using our official SDK.

#### Python Example

```
import requests
​
# Use API Token to call APIs
token = "tk_your_api_token"
headers = {"X-API-Token": token}
​
# Get agents list
response = requests.get("https://api.deepcore.top/api/agents", headers=headers)
agents = response.json()["data"]
print(agents)
```

#### JavaScript Example

```
// Use API Token to call APIs
const token = "tk_your_api_token";
​
// Get agents list
fetch("https://api.deepcore.top/api/agents", {
  headers: {
    "X-API-Token": token
  }
})
.then(response => response.json())
.then(data => {
  console.log(data.data);
});
```

### Rate Limits

To ensure service quality, API requests have the following limitations:

* Maximum 60 requests per minute per IP address
* Maximum 120 requests per minute per user
* Maximum 10 chat API requests per minute per user

Exceeding these limits will result in HTTP 429 status code.

### More Information

For more information and detailed documentation about the API, please visit [DeepCore Official Documentation](https://docs.deepcore.top/).


# DeepCore A2A

## DeepCore A2A

### Summary

This whitepaper presents DeepCore's implementation of the Agent-to-Agent (A2A) Protocol, an open standard designed to facilitate communication between independent AI agent systems. DeepCore's A2A integration enables seamless interaction between agents built on different frameworks, supporting streamlined task management, multi-format messaging, and real-time streaming capabilities.

### 1. Introduction

The AI agent ecosystem is rapidly evolving, with diverse agents built using different technologies and frameworks. The Agent-to-Agent (A2A) Protocol, developed by Google, addresses the critical need for standardized communication between these heterogeneous agent systems. DeepCore has implemented a comprehensive A2A solution that enables agents to discover capabilities, exchange complex information, and collaborate effectively.

This implementation is built upon the official [Google A2A Protocol Specification](https://google.github.io/A2A/specification/), ensuring full compatibility with the standard and interoperability with other A2A-compatible systems. DeepCore extends the core protocol with additional capabilities while maintaining strict adherence to the specification's requirements for message formats, task management, and agent discovery mechanisms.

### 2. A2A Protocol Overview

The A2A Protocol provides a standardized approach for agent communication with the following core features:

* **Agent Discovery**: Mechanisms for agents to discover each other's capabilities
* **Task Management**: Protocols for task creation, monitoring, and lifecycle management
* **Message Exchange**: Standards for transferring text, files, and structured data
* **Streaming Communication**: Real-time event-based interaction patterns
* **Security**: Standards for authentication and authorization

### 3. DeepCore A2A Architecture

DeepCore's A2A implementation follows a layered architecture:

```
┌─────────────────────────────────────┐
│           A2A HTTP Router           │
├─────────────────────────────────────┤
│        DeepCore A2A Agent           │
├─────────────────────────────────────┤
│       Agent Service Integration     │
├─────────────────────────────────────┤
│         Redis Task Storage          │
└─────────────────────────────────────┘
```

#### 3.1 Key Components

* **DeepCore A2A Agent**: Adapts existing DeepCore agents to the A2A protocol
* **A2A HTTP Router**: Handles HTTP endpoints for the A2A protocol operations
* **Agent Service Integration**: Connects to existing DeepCore agent services
* **Redis-based Task Storage**: Manages persistent task state

### 4. Core Features and Capabilities

#### 4.1 Agent Discovery via Agent Cards

DeepCore agents expose their capabilities through A2A Agent Cards, allowing other agents to discover:

* Basic agent information (name, description, version)
* Supported capabilities (streaming, push notifications)
* Available skills and tools
* Authentication requirements

```
# Agent Card creation example
agent_card = AgentCard(
    name=self.agent_data.get("name", "DeepCore Agent"),
    description=self.agent_data.get("description", ""),
    url=base_url,
    version="1.0.0",
    capabilities={
        "streaming": True,
        "pushNotifications": False,
        "stateTransitionHistory": False,
        "google_a2a_compatible": True,
        "parts_array_format": True
    },
    skills=skills,
)
```

#### 4.2 Multi-Format Message Handling

DeepCore's A2A implementation supports multiple message formats:

* Standard A2A protocol format
* Google A2A format with parts-based messaging
* Auto-format detection and conversion

#### 4.3 Task Lifecycle Management

The implementation provides comprehensive task management:

* Creation and tracking of tasks
* Task state persistence via Redis
* Task status monitoring
* Task cancellation capabilities

```
# Task lifecycle example
async def handle_task(self, task):
    # Process task
    # ...
    # Mark task as completed
    task.status = TaskStatus(state=TaskState.COMPLETED)
    # Store task state
    self._save_task(task)
    return task
```

#### 4.4 Real-time Streaming Communication

DeepCore's A2A implementation provides robust streaming capabilities using Server-Sent Events (SSE):

* Streaming message responses
* Task status updates
* Progress notifications
* Error handling

### 5. Implementation Details

#### 5.1 Message Processing Flow

When a message is received through the A2A endpoint:

1. The HTTP router receives and validates the request
2. Format detection logic identifies message structure (standard A2A or Google A2A)
3. The message is converted to the appropriate internal format
4. The DeepCoreA2AAgent processes the message using the agent service
5. The response is formatted according to the detected input format
6. The HTTP router returns the response

#### 5.2 Task Management

Tasks in DeepCore's A2A implementation:

1. Are uniquely identified with UUIDs
2. Have a defined lifecycle (created, running, completed, failed, canceled)
3. Are persisted in Redis for reliability
4. Can be monitored through polling or SSE streaming

#### 5.3 Format Compatibility

DeepCore's implementation ensures compatibility through:

* Format auto-detection
* Message format conversion
* Support for both standard A2A and Google A2A formats
* Format preference persistence

### 6. API Endpoints

DeepCore's A2A implementation exposes the following key endpoints:

* `GET /A2A/{agent_id}/` - Agent discovery endpoint
* `GET /A2A/{agent_id}/agent.json` - Agent card endpoint
* `POST /A2A/{agent_id}/` - Message handling endpoint
* `POST /A2A/{agent_id}/stream` - Streaming endpoint
* `POST /A2A/{agent_id}/tasks/send` - Task submission endpoint
* `POST /A2A/{agent_id}/tasks/get` - Task status endpoint
* `POST /A2A/{agent_id}/tasks/cancel` - Task cancellation endpoint
* `POST /A2A/{agent_id}/tasks/stream` - Task streaming endpoint

### 7. Use Cases

DeepCore's A2A implementation enables various interaction patterns:

#### 7.1 Simple Question-Answer

Clients can send simple queries to agents and receive direct responses.

#### 7.2 Multi-turn Conversations

Agents can maintain conversation context for complex interactions requiring multiple exchanges.

#### 7.3 Collaborative Task Execution

Multiple agents can work together by delegating subtasks and exchanging intermediate results.

#### 7.4 Real-time Progress Monitoring

Clients can monitor long-running tasks through streaming updates.

### 8. Code Examples

DeepCore's A2A implementation can be easily integrated with the python-a2a library. Here are practical examples of how to interact with DeepCore agents using the library:

#### 8.1 Basic Message Interaction

Send a simple message to a DeepCore agent and get a response:

```
import asyncio
from python_a2a import A2AClient, Message, TextContent, MessageRole
​
async def basic_message_example(agent_id, token):
    # Initialize the client with the agent's endpoint
    client = A2AClient(
        f"https://deepcore.top/A2A/{agent_id}",
        headers={"X-API-Token": f"{token}"}
    )
    
    # Create a message
    message = Message(
        content=TextContent(text="What is the Agent-to-Agent protocol?"),
        role=MessageRole.USER
    )
    
    # Send the message and wait for response
    try:
        response = await client.send_message(message)
        print(f"Agent response: {response.content.text}")
        return response
    except Exception as e:
        print(f"Error communicating with agent: {e}")
        return None
​
# Run the example
if __name__ == "__main__":
    agent_id = "your_agent_id"
    token = "your_api_token"
    asyncio.run(basic_message_example(agent_id, token))
```

#### 8.2 Streaming Responses

Get real-time streaming responses from a DeepCore agent:

```
import asyncio
from python_a2a import StreamingClient, Message, TextContent, MessageRole
​
async def streaming_example(agent_id, token):
    # Initialize streaming client
    client = StreamingClient(
        f"https://deepcore.top/A2A/{agent_id}",
        headers={"X-API-Token": f"{token}"}
    )
    
    # Create a message
    message = Message(
        content=TextContent(text="Tell me about A2A streaming capabilities"),
        role=MessageRole.USER
    )
    
    # Stream the response
    try:
        print("Streaming response:")
        async for chunk in client.stream_response(message):
            if 'content' in chunk:
                print(chunk['content'], end="", flush=True)
            # Check for last chunk
            if chunk.get('lastChunk', False):
                print("\nStream complete")
                break
    except Exception as e:
        print(f"\nStreaming error: {e}")
​
# Run the example
if __name__ == "__main__":
    agent_id = "your_agent_id"
    token = "your_api_token"
    asyncio.run(streaming_example(agent_id, token))
```

#### 8.3 Task Management

Create, monitor, and manage tasks:

```
import asyncio
import time
from python_a2a import A2AClient, Task, Message, TextContent, MessageRole
​
async def task_management_example(agent_id, token):
    # Initialize the client
    client = A2AClient(
        f"https://deepcore.top/A2A/{agent_id}",
        headers={"X-API-Token": f"{token}"}
    )
    
    # Create a message
    message = Message(
        content=TextContent(text="Generate a comprehensive report on renewable energy"),
        role=MessageRole.USER
    )
    
    # Create a task
    task_id = f"task-{int(time.time())}"
    task = Task(
        id=task_id,
        message=message
    )
    
    try:
        # Send the task
        print(f"Submitting task {task_id}...")
        submitted_task = await client.send_task(task)
        print(f"Task submitted with ID: {submitted_task.id}")
        print(f"Initial status: {submitted_task.status.state}")
        
        # Poll for task completion
        max_attempts = 10
        for attempt in range(max_attempts):
            # Wait before checking status
            await asyncio.sleep(2)
            
            # Check task status
            task_status = await client.get_task(task_id)
            print(f"Task status ({attempt+1}/{max_attempts}): {task_status.status.state}")
            
            # If task is complete, show results
            if task_status.status.state in ["completed", "failed", "canceled"]:
                if task_status.artifacts:
                    print("\nTask results:")
                    for artifact in task_status.artifacts:
                        for part in artifact.get("parts", []):
                            if part.get("type") == "text":
                                print(f"- {part.get('text')}")
                break
                
        # Task can be canceled if needed
        # await client.cancel_task(task_id)
        
    except Exception as e:
        print(f"Error in task management: {e}")
​
# Run the example
if __name__ == "__main__":
    agent_id = "your_agent_id"
    token = "your_api_token"
    asyncio.run(task_management_example(agent_id, token))
```

#### 8.4 Agent Networks

Work with multiple DeepCore agents as a coordinated network:

```
import asyncio
from python_a2a import AgentNetwork, Message, TextContent, MessageRole
​
async def agent_network_example(token):
    # Create an agent network
    network = AgentNetwork(name="DeepCore Specialized Agents")
    
    # Add multiple agents to the network
    network.add("research", 
                f"https://deepcore.top/A2A/research_agent", 
                headers={"X-API-Token": f"{token}"})
    
    network.add("coding", 
                f"https://deepcore.top/A2A/code_agent", 
                headers={"X-API-Token": f"{token}"})
    
    network.add("data_analysis", 
                f"https://deepcore.top/A2A/data_agent", 
                headers={"X-API-Token": f"{token}"})
    
    # List all agents in the network
    print("Agents in network:")
    for agent_info in network.list_agents():
        print(f"- {agent_info['name']} at {agent_info['url']}")
    
    # Send messages to specific agents based on the task type
    try:
        # Research query to research agent
        research_agent = network.get_agent("research")
        research_message = Message(
            content=TextContent(text="What are the latest advancements in quantum computing?"),
            role=MessageRole.USER
        )
        research_response = await research_agent.send_message(research_message)
        print("\nResearch Agent Response:")
        print(research_response.content.text[:300] + "...")
        
        # Coding query to coding agent
        code_agent = network.get_agent("coding")
        code_message = Message(
            content=TextContent(text="Write a Python function to calculate Fibonacci numbers"),
            role=MessageRole.USER
        )
        code_response = await code_agent.send_message(code_message)
        print("\nCoding Agent Response:")
        print(code_response.content.text[:300] + "...")
        
    except Exception as e:
        print(f"Error in agent network communication: {e}")
​
# Run the example
if __name__ == "__main__":
    token = "your_api_token"
    asyncio.run(agent_network_example(token))
```

#### 8.5 Integration with External Tools

Connect DeepCore agents with external tools using the Model Context Protocol (MCP):

```
import asyncio
from python_a2a import A2AClient, Message, TextContent, MessageRole, FunctionCallContent, FunctionResponseContent
​
async def tool_integration_example(agent_id, token):
    # Initialize the client
    client = A2AClient(
        f"https://deepcore.top/A2A/{agent_id}",
        headers={"X-API-Token": f"{token}"}
    )
    
    # Create a message requesting weather information
    message = Message(
        content=TextContent(text="What's the weather like in New York?"),
        role=MessageRole.USER
    )
    
    try:
        # Send the message
        response = await client.send_message(message)
        
        # Check if the response is a function call (tool request)
        if hasattr(response.content, 'type') and response.content.type == 'function_call':
            function_name = response.content.name
            parameters = response.content.parameters
            
            print(f"Agent requested tool: {function_name}")
            print(f"Parameters: {parameters}")
            
            # Simulate calling an external weather API
            if function_name == "get_weather":
                # In a real implementation, you would call an actual weather API here
                weather_data = {
                    "location": parameters.get("location", "New York"),
                    "temperature": 72,
                    "conditions": "Partly Cloudy",
                    "humidity": 65
                }
                
                # Send function response back to the agent
                function_response = Message(
                    content=FunctionResponseContent(
                        name=function_name,
                        response=weather_data
                    ),
                    role=MessageRole.FUNCTION
                )
                
                # Get final response after providing the tool result
                final_response = await client.send_message(function_response)
                print("\nFinal agent response after tool use:")
                print(final_response.content.text)
            else:
                print(f"Unknown function: {function_name}")
        else:
            # Direct response without tool use
            print("\nDirect agent response:")
            print(response.content.text)
            
    except Exception as e:
        print(f"Error in tool integration: {e}")
​
# Run the example
if __name__ == "__main__":
    agent_id = "your_agent_id"
    token = "your_api_token"
    asyncio.run(tool_integration_example(agent_id, token))
```

### 8.6 DeepCore A2A Resources

For more information and to get started with DeepCore's A2A implementation, visit the following resources:

* **Main A2A Endpoint**: <https://deepcore.top/a2a>
* **API Documentation**: [https://docs.deepcore.top/](https://deepcore.top/docs/api/a2a)
* **Python A2A Library**: <https://github.com/themanojdesai/python-a2a>
* **A2A Protocol Specification**: <https://google.github.io/A2A/specification/>

### 9. Security Considerations

DeepCore's A2A implementation addresses several security aspects:

* Transport security through HTTPS
* Authentication through standard HTTP mechanisms
* Authorization based on agent and user identity
* Input validation to prevent injection attacks
* Resource management to prevent abuse

### 10. Future Directions

The DeepCore A2A implementation roadmap includes:

* Enhanced push notification support
* Multi-agent orchestration capabilities
* Advanced authentication mechanisms
* Expanded file exchange capabilities
* Structured data schema negotiation

### 11. Conclusion

DeepCore's A2A implementation provides a robust framework for agent-to-agent communication, enabling interoperability between diverse AI systems. By adhering to the A2A protocol standard while supporting flexible message formats, DeepCore enables seamless integration between heterogeneous agent ecosystems.

The implementation's support for task management, streaming communication, and format compatibility positions DeepCore as a versatile platform for building complex multi-agent systems that can effectively collaborate to achieve user goals.


# DeepCore MCP

MCP THE FUTURE

## DeepCore MCP Documentation

### What is MCP

MCP (Model Context Protocol) is an open standard for building secure bi-directional connections, allowing AI models to interact with data sources. Through MCP, developers can:

* Expose their data to AI models via MCP servers
* Build AI applications (MCP clients) that connect to these servers
* Enable AI models to maintain context across different tools and datasets

MCP addresses the challenges of AI systems accessing data, replacing traditional fragmented integration approaches with a universal open standard.

### MCP Implementation in DeepCore

DeepCore implements complete MCP server functionality, allowing users to package their tools and data as MCP services for AI models to use. In DeepCore, MCP services are divided into two types:

1. **Built-in MCP services**: System-predefined services such as `coin-api`
2. **MCP Tool Importing**: Support for importing tools from external MCP services into the DeepCore tool marketplace, enabling easy integration of third-party capabilities
3. **Dynamic MCP services**: Custom MCP services created by users through the API

#### Core Components

DeepCore's MCP implementation contains the following core components:

* **MCP Server**: Provides the ability to interact with AI models through SSE (Server-Sent Events)
* **MCP Tools**: Functional units encapsulated in the MCP server, typically representing API calls
* **MCP Prompt Templates**: Prompt templates that help AI better use MCP tools
* **MCP Resources**: Static content that MCP services can access

### MCP Server Architecture

<figure><img src="https://1759951032-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvilI5gkHSwBtnpgNfbRd%2Fuploads%2FC7t5CIZHPV4kVi1RxJp8%2Fimage.png?alt=media&amp;token=d4466d2c-add4-41fb-a693-45016d333c49" alt=""><figcaption></figcaption></figure>

DeepCore's MCP implementation uses SSE as the transport layer, based on the following architecture:

1. AI model/client initiates SSE connection to the MCP server endpoint
2. Client can request tool lists, call tools, get prompts, access resources, etc.
3. MCP server processes requests and returns responses via SSE stream
4. All interactions use standardized MCP formats

#### Token Authentication

DeepCore uses API Token authentication for accessing all MCP-related APIs. This method is simple to implement and suitable for both development and production environments.

For detailed information on authentication methods, obtaining and using API Tokens, please refer to the [DeepCore API Documentation](https://docs.deepcore.top/deepcore-guide/deepcore-api).

{% code lineNumbers="true" %}

```
import requests
​
# Use API Token to call interfaces
headers = {"X-API-Token": "tk_your_api_token"}  # Replace with your API Token from the DeepCore platform
​
# Example: Create an MCP service
response = requests.post(
    "https://api.deepcore.top/api/mcp/create",
    headers=headers,
    json={
        "mcp_name": "my-service",
        "tool_ids": ["00000000-0000-0000-0000-000000000001"],
        "description": "My MCP Service"
    }
)
​
print(response.json())
```

{% endcode %}

#### Prerequisites

* Registered DeepCore account and obtained API token
* Created or accessed certain tools (via the `/api/tools` endpoint)

### Importing MCP Service Tools

DeepCore provides API interfaces that allow users to import tools from existing MCP services. This makes it easy to integrate functionality from third-party MCP services into your own DeepCore tool set for use in custom AI applications.

#### Process for Importing MCP Tools

1. **Parse MCP service URL**: Use the `/api/tools/parse-mcp` interface to analyze an MCP service and obtain its tool definitions
2. **Batch create tools**: Use the `/api/tools/create-batch` interface to batch import the parsed tools into your account

#### Example: Parsing MCP Services

The following example shows how to parse an existing MCP service and get its tool definitions:

{% code lineNumbers="true" %}

```
import requests
​
# Use API Token for authentication
api_token = "tk_your_api_token"  # Replace with your actual API Token
headers = {"X-API-Token": api_token}
​
# Parse MCP service URL
response = requests.post(
    "https://api.deepcore.top/api/tools/parse-mcp",
    headers=headers,
    json={"mcp_url": "https://api.deepcore.top/mcp/weather-service"}
)
​
# Get parsing results
parse_result = response.json()["data"]
print(f"Successfully parsed MCP service: {parse_result['url']}")
print(f"Number of tools discovered: {len(parse_result['api_info'])}")
​
# Display parsed tools
for i, tool in enumerate(parse_result['api_info']):
    print(f"Tool {i+1}: {tool['name']} - {tool.get('description', 'No description')}")
```

{% endcode %}

#### Example: Batch Importing Tools

After obtaining tool definitions by parsing an MCP service, you can use the following code to batch import these tools into your account:

{% code lineNumbers="true" %}

```
import requests
​
# Use API Token for authentication
api_token = "tk_your_api_token"  # Replace with your actual API Token
headers = {"X-API-Token": api_token}
​
# Assuming parse_result has been obtained (result from previous step)
# Build batch tool creation request
tools_to_create = []
for tool_info in parse_result['api_info']:
    # Build import configuration for each tool
    tool_config = {
        "name": f"MCP Import: {tool_info['name']}",
        "description": tool_info.get('description', 'Tool imported from MCP service'),
        "origin": parse_result['url'],  # MCP service URL as tool source
        "path": tool_info.get('path', ''),
        "method": tool_info.get('method', 'GET'),
        "parameters": tool_info.get('parameters', []),
        "auth_config": None,  # No extra authentication needed for calls via MCP
        "is_mcp_tool": True   # Mark as MCP tool
    }
    tools_to_create.append(tool_config)
​
# Batch create tools
response = requests.post(
    "https://api.deepcore.top/api/tools/create-batch",
    headers=headers,
    json={"tools": tools_to_create}
)
​
# Check results
result = response.json()
if result.get("code") == 0:
    created_tools = result["data"]
    print(f"Successfully imported {len(created_tools)} tools")
    for tool in created_tools:
        print(f"- Tool ID: {tool['id']}, Name: {tool['name']}")
else:
    print(f"Failed to import tools: {result.get('msg', 'Unknown error')}")
```

{% endcode %}

#### Benefits of Importing MCP Tools

1. **Functionality Reuse**: No need to redevelop existing MCP tool functionality
2. **Service Integration**: Combine tools from multiple MCP services into one custom MCP service
3. **Feature Customization**: Selectively import needed tools, reject unwanted ones
4. **Permission Control**: Apply your own access control policies to imported tools
5. **Better Integration**: Seamlessly integrate third-party MCP service tools with your own developed tools

### Creating MCP Services

#### Steps to Create an MCP Service

1. **Select tools**: Determine which tools to expose in the MCP service
2. **Create MCP server**: Call the `/api/mcp/create` API to create an MCP server
3. **Add prompt templates (optional)**: Add prompt templates via `/api/mcp/{mcp_name}/prompts`
4. **Add resources (optional)**: Add resources via `/api/mcp/{mcp_name}/resources`

#### Getting Tool IDs

When creating an MCP service, you need to provide a list of tool IDs to include. These IDs must be existing tool IDs in the DeepCore platform. Here's how to get available tool IDs:

<pre data-line-numbers><code>import requests
<strong>​
</strong># Use API Token for authentication
api_token = "tk_your_api_token"  # Replace with your actual API Token
headers = {"X-API-Token": api_token}
​
# Get list of available tools
response = requests.get(
    "https://api.deepcore.top/api/tools/list",
    headers=headers,
    params={
        "include_public": True,    # Include public tools
        "page": 1,                 # Page number
        "page_size": 50            # Number of tools per page
    }
)
​
# Parse tool list
tools_data = response.json()["data"]
available_tools = tools_data["items"]
​
# Display available tools and their IDs
print("Available tools list:")
for tool in available_tools:
    print(f"ID: {tool['id']} - Name: {tool['name']} - Description: {tool.get('description', 'No description')}")
​
# Select tool IDs to include in the MCP service
selected_tool_ids = [
    "00000000-0000-0000-0000-000000000001",  # Example ID, replace with actual tool ID
    "00000000-0000-0000-0000-000000000002"   # Example ID, replace with actual tool ID
]
</code></pre>

#### Example: Creating an MCP Service

Here's a complete example showing how to create an MCP service using an API Token:

{% code lineNumbers="true" %}

```
import requests
​
# Use API Token
api_token = "tk_your_api_token"  # Replace with your actual API Token
headers = {"X-API-Token": api_token}
​
# Step 1: Get list of available tools
response = requests.get(
    "https://api.deepcore.top/api/tools/list",
    headers=headers,
    params={"include_public": True, "page": 1, "page_size": 10}
)
tools_data = response.json()["data"]["items"]
available_tool_ids = [tool["id"] for tool in tools_data]
print(f"Available tool IDs: {available_tool_ids}")
​
# Step 2: Create MCP service
response = requests.post(
    "https://api.deepcore.top/api/mcp/create",
    headers=headers,
    json={
        "mcp_name": "sample-service",
        "tool_ids": available_tool_ids[:2],  # Use the first two tools
        "description": "MCP Service Example Created with API Token"
    }
)
mcp_data = response.json()["data"]
print(f"MCP service created: {mcp_data['mcp_name']}")
​
# Step 3: Add prompt template
response = requests.post(
    f"https://api.deepcore.top/api/mcp/{mcp_data['mcp_name']}/prompts",
    headers=headers,
    json={
        "prompt_name": "sample-prompt",
        "description": "Example prompt template",
        "arguments": [
            {"name": "param1", "description": "Parameter 1", "required": True}
        ],
        "template": "Use {{ param1 }} as a parameter"
    }
)
print(f"Prompt template added: {response.json()}")
​
# Step 4: Add resource
response = requests.post(
    f"https://api.deepcore.top/api/mcp/{mcp_data['mcp_name']}/resources",
    headers=headers,
    json={
        "resource_uri": "sample.txt",
        "content": "This is an example resource content",
        "mime_type": "text/plain"
    }
)
print(f"Resource added: {response.json()}")
```

{% endcode %}

#### Example: Adding Prompt Templates

{% code lineNumbers="true" %}

```
response = requests.post(
    "https://api.deepcore.top/api/mcp/weather-service/prompts",
    headers=headers,
    json={
        "prompt_name": "check-weather",
        "description": "Query weather information for a specified city",
        "arguments": [
            {"name": "city", "description": "City name", "required": True},
            {"name": "date", "description": "Date (optional)", "required": False}
        ],
        "template": "Help me check the weather in {{ city }}{% if date %}, the date is {{ date }}{% endif %}"
    }
)
​
print(response.json())
```

{% endcode %}

#### Example: Adding Resources

{% code lineNumbers="true" %}

```
response = requests.post(
    "https://api.deepcore.top/api/mcp/weather-service/resources",
    headers=headers,
    json={
        "resource_uri": "cities.txt",
        "content": "New York\nLosAngeles\nChicago\nPhiladelphia\n...",
        "mime_type": "text/plain"
    }
)
​
print(response.json())
```

{% endcode %}

### MCP Server Internal Implementation

DeepCore's MCP server internal implementation is based on the Python MCP server library and integrated with FastAPI. Main components include:

1. **SseServerTransport**: Provides an SSE-based transport layer
2. **Server**: MCP server core class, handles requests and responses
3. **Handlers**: Registered handler functions, including:
   * `list_tools` - List available tools
   * `call_tool` - Call tools
   * `list_prompts` - List prompt templates
   * `get_prompt` - Get specific prompts
   * `list_resources` - List resources
   * `read_resource` - Read resource content

#### Core Implementation

DeepCore's MCP implementation encapsulates tools into MCP tool format, automatically converting parameter structures and response formats to ensure compliance with MCP specifications. Each MCP service is stored in the database, including basic service information, associated tools, prompts, and resources.

Dynamic MCP service creation process:

1. Create `MCPServer` record in the database
2. Associate `MCPTool` records pointing to existing tools
3. Optionally add `MCPPrompt` and `MCPResource` records
4. Process requests through routing, dynamically creating MCP server instances

### Using MCP Services

#### Client Connection

AI models or clients can connect to MCP server endpoints via SSE:

```
GET https://api.deepcore.top/mcp/{mcp_name}
```

#### Available Operations

Once connected, clients can perform the following operations:

1. **List tools**: Get list of available tools
2. **Call tools**: Execute tool operations and get results
3. **List prompts**: Get list of available prompt templates
4. **Get prompts**: Get specific prompt templates and fill variables
5. **List resources**: Get list of available resources
6. **Read resources**: Get resource content

#### Example: AI Model Using MCP Service

When an AI model (like Claude) connects to an MCP service, it can:

```
Model: I need to know the weather in New York
MCP Service: [Lists tools, including a weather query tool]
Model: [Calls the weather query tool with parameter city="New York"]
MCP Service: [Returns weather information for New York]
Model: Thank you, this information is very helpful
```

### Using Python Client to Connect to MCP Services

DeepCore MCP services can be connected to and used through various client libraries. Below is how to use the official `mcp` library and `mirascope` library to connect to DeepCore-provided MCP services.

#### Installing Dependencies

First, install the necessary dependency packages:

```
pip install mcp mirascope
```

#### Example of Using Mirascope to Connect to MCP Services

Here's a basic example showing how to use the mirascope library to connect to a DeepCore MCP service and list available tools:

{% code lineNumbers="true" %}

```
import asyncio
from mcp import ListToolsResult
from mirascope.mcp import sse_client
​
async def main():
    # Connect to DeepCore MCP service
    async with sse_client("https://api.deepcore.top/mcp/mcpAggService") as client:
        # List available tools
        tools: ListToolsResult = await client._session.list_tools()
        print(tools)
​
if __name__ == "__main__":
    asyncio.run(main())
```

{% endcode %}

#### Example: Calling MCP Tools

The following example shows how to call tools in an MCP service:

{% code lineNumbers="true" %}

```
import asyncio
from mcp import CallToolResult
from mirascope.mcp import sse_client
​
async def main():
    async with sse_client("https://api.deepcore.top/mcp/weather-service") as client:
        # First list all tools
        tools = await client._session.list_tools()
        print(f"Available tools: {[tool.name for tool in tools.tools]}")
        
        # Call the weather query tool
        tool_result: CallToolResult = await client._session.call_tool(
            name="query-weather",
            arguments={"city": "New York", "date": "today"}
        )
        
        # Print tool execution results
        for content in tool_result.contents:
            if content.type == "text":
                print(f"Result: {content.text}")
            elif content.type == "image":
                print(f"Image URL: {content.url}")
​
if __name__ == "__main__":
    asyncio.run(main())
```

{% endcode %}

#### Example: Listing and Using Prompt Templates

{% code lineNumbers="true" %}

```
import asyncio
from mirascope.mcp import sse_client
​
async def main():
    async with sse_client("https://api.deepcore.top/mcp/weather-service") as client:
        # List all prompt templates
        prompts = await client._session.list_prompts()
        print(f"Available prompts: {[prompt.name for prompt in prompts.prompts]}")
        
        # Get specific prompt
        if prompts.prompts:
            prompt_name = prompts.prompts[0].name
            prompt = await client._session.get_prompt(
                name=prompt_name,
                arguments={"city": "Shanghai", "date": "tomorrow"}
            )
            print(f"Prompt content: {prompt.text}")
​
if __name__ == "__main__":
    asyncio.run(main())
```

{% endcode %}

#### Example: Reading Resources

{% code lineNumbers="true" %}

```
import asyncio
from mirascope.mcp import sse_client
​
async def main():
    async with sse_client("https://api.deepcore.top/mcp/weather-service") as client:
        # List all resources
        resources = await client._session.list_resources()
        print(f"Available resources: {[resource.uri for resource in resources.resources]}")
        
        # Read specific resource
        if resources.resources:
            resource_uri = resources.resources[0].uri
            resource = await client._session.read_resource(uri=resource_uri)
            print(f"Resource content: {resource.content.text[:100]}...") # Only display first 100 characters
​
if __name__ == "__main__":
    asyncio.run(main())
```

{% endcode %}

### Multilingual SDK Support

Model Context Protocol provides SDKs in multiple programming languages that can seamlessly integrate with DeepCore MCP services. Below are the usage methods for various language SDKs, allowing developers to choose their familiar language to use MCP services.

#### TypeScript/JavaScript SDK

TypeScript SDK is one of the official implementations of Model Context Protocol, suitable for Node.js and browser environments.

**Installation**

```
npm install @modelcontextprotocol/typescript-sdk
```

**Usage Example**

{% code lineNumbers="true" %}

```
import { createClient } from '@modelcontextprotocol/typescript-sdk';
​
async function main() {
  // Create MCP client
  const client = await createClient('https://api.deepcore.top/mcp/mcpAggService');
  
  try {
    // Get available tools list
    const tools = await client.listTools();
    console.log('Available tools:', tools.tools.map(tool => tool.name));
    
    if (tools.tools.length > 0) {
      // Call the first tool
      const toolName = tools.tools[0].name;
      const result = await client.callTool(toolName, {
        // Tool parameters
        param1: 'value1',
        param2: 'value2'
      });
      
      // Process results
      for (const content of result.contents) {
        if (content.type === 'text') {
          console.log('Result:', content.text);
        }
      }
    }
  } finally {
    // Close client connection
    await client.close();
  }
}
​
main().catch(console.error);
```

{% endcode %}

For more details and advanced usage, please refer to the [TypeScript SDK Official Repository](https://github.com/modelcontextprotocol/typescript-sdk).

#### Java SDK

Java SDK provides functionality for using MCP in Java applications, with good integration with Spring AI.

**Adding Dependencies**

```
<!-- Maven -->
<dependency>
  <groupId>io.modelcontextprotocol</groupId>
  <artifactId>mcp-java-sdk</artifactId>
  <version>latest-version</version>
</dependency>
```

Or

```
// Gradle
implementation 'io.modelcontextprotocol:mcp-java-sdk:latest-version'
```

**Usage Example**

{% code lineNumbers="true" %}

```
import io.modelcontextprotocol.client.MCPClient;
import io.modelcontextprotocol.client.MCPClientBuilder;
import io.modelcontextprotocol.types.CallToolResult;
import io.modelcontextprotocol.types.ListToolsResult;
import io.modelcontextprotocol.types.Tool;
import io.modelcontextprotocol.types.Content;
​
import java.util.HashMap;
import java.util.Map;
​
public class MCPExample {
    public static void main(String[] args) throws Exception {
        // Create MCP client
        try (MCPClient client = MCPClientBuilder.create("https://api.deepcore.top/mcp/mcpAggService").build()) {
            
            // Get available tools list
            ListToolsResult toolsResult = client.listTools();
            System.out.println("Available tools:");
            for (Tool tool : toolsResult.getTools()) {
                System.out.println("- " + tool.getName() + ": " + tool.getDescription());
            }
            
            if (!toolsResult.getTools().isEmpty()) {
                // Call the first tool
                String toolName = toolsResult.getTools().get(0).getName();
                Map<String, Object> arguments = new HashMap<>();
                arguments.put("param1", "value1");
                arguments.put("param2", "value2");
                
                CallToolResult result = client.callTool(toolName, arguments);
                
                // Process results
                for (Content content : result.getContents()) {
                    if ("text".equals(content.getType())) {
                        System.out.println("Result: " + content.getText());
                    }
                }
            }
        }
    }
}
```

{% endcode %}

For more details and advanced usage, please refer to the [Java SDK Official Repository](https://github.com/modelcontextprotocol/java-sdk).

### Advantages of MCP Services

Using DeepCore MCP services offers the following advantages:

1. **Standardized Interface**: Use a unified protocol to connect different data sources
2. **Secure Access**: Controlled data access methods
3. **Context Preservation**: AI models can maintain context across different tools
4. **Simplified Integration**: No need to maintain separate connectors for each data source
5. **Scalability**: Easily add new tools and data sources

### Practical Application Scenarios

#### 1. Knowledge Base Access

Create MCP services connected to enterprise knowledge bases, allowing AI models to query and retrieve specific information.

#### 2. Data Analysis Tools

Encapsulate data analysis functionality as MCP tools, enabling AI models to execute data queries and analysis.

#### 3. Internal System Integration

Package internal system APIs as MCP services, giving AI assistants access to these functionalities.

#### 4. Specialized Domain Tools

Create collections of specialized domain tools (such as finance, healthcare) and provide them to AI models through MCP.

### Best Practices

1. **Tool Design**: Design simple, single-function tools rather than complex multi-function tools
2. **Provide Clear Descriptions**: Give clear descriptions for tools and parameters
3. **Add Prompt Templates**: Help AI models better understand and use tools
4. **Resource Management**: Provide commonly used information as resources to reduce repeated queries
5. **Permission Control**: Pay attention to access permission control for MCP services

### Limitations and Considerations

1. MCP services currently only support synchronous calls, not long-running asynchronous operations
2. There are size limitations on data returned by tools; avoid returning overly large datasets
3. Be careful to protect sensitive information and authentication credentials
4. MCP server instances are created with each request, they don't maintain long-term state

### Troubleshooting

Common issues and solutions:

1. **Connection Problems**: Check if the MCP service name is correct, confirm the service has been created
2. **Authentication Errors**: Verify user permissions and authentication tokens
3. **Tool Call Failures**: Check tool configuration and parameter formats
4. **Resource Access Failures**: Confirm resources have been added and are in the correct format

### Summary

DeepCore MCP services provide a standardized way for AI models to securely and effectively access and operate various tools and data sources. Through simple API calls, developers can create powerful MCP services, extending the capability range of AI models and building smarter, more practical AI applications.


# Large Model Agents

## Principles of Large Model Agents and Web3 Integration Advantages

### 1. In-Depth Principles of Large Model Agents

Large model agents are powered by extensive pre-training on massive datasets using advanced deep learning architectures. Key theoretical principles include:

#### 1.1 Transformer Architecture and Self-Attention

At the heart of modern large models (e.g., GPT-4, GPT-3.5) is the Transformer architecture. This design eliminates recurrence by using multi-head self-attention mechanisms, allowing the model to weigh the importance of different tokens in an input sequence. For example, in self-attention, each token in the input computes a weighted representation of every other token:

```
import numpy as np
from math import sqrt
​
def self_attention(query, key, value, mask=None):
    # Compute scaled dot-product attention
    scores = np.dot(query, key.T) / sqrt(query.shape[-1])
    if mask is not None:
        scores += (mask * -1e9)
    attention_weights = np.exp(scores) / np.sum(np.exp(scores), axis=-1, keepdims=True)
    output = np.dot(attention_weights, value)
    return output
```

This mechanism enables the model to capture long-range dependencies and subtle contextual nuances, forming the basis for high-quality natural language understanding and generation.

#### 1.2 Scaling Laws and Fine-Tuning

Research on scaling laws demonstrates that as models grow larger and are trained on more data, their performance improves predictably. Pre-training on diverse datasets allows these models to learn generalized representations, which can then be fine-tuned on domain-specific tasks to achieve exceptional performance.

#### 1.3 Hierarchical Semantic Representations

Large models build multi-layered representations of language, where lower layers capture basic syntax and word embeddings, while higher layers encode complex semantics and abstract reasoning. This hierarchy is essential for tasks that require deep understanding and context-based responses.

#### 1.4 Emergent Abilities and Generalization

As model sizes increase, emergent properties such as zero-shot learning and few-shot adaptation appear. These abilities allow large models to perform tasks they were not explicitly trained for, revealing the power of unsupervised learning and massive data ingestion.

### 2. Fundamental Principles of Web3

Web3 represents the next evolution of the internet by emphasizing decentralization, transparency, and security. Its foundational principles include:

#### 2.1 Decentralized Ledger and Consensus Algorithms

At the core of Web3 is blockchain technology—a decentralized ledger maintained by a network of nodes. Consensus mechanisms such as Proof of Work (PoW) or Proof of Stake (PoS) ensure that all participants agree on the state of the ledger. This decentralized consensus eliminates the need for a central authority and makes the system resilient to tampering.

#### 2.2 Cryptographic Security

Web3 relies on advanced cryptographic techniques to secure transactions and data. Public-key cryptography enables users to sign transactions digitally, ensuring authenticity and non-repudiation. Digital signatures and hashing functions protect data integrity and prevent unauthorized modifications.

#### 2.3 Smart Contracts

Smart contracts are self-executing contracts with the terms directly written in code. They automatically enforce and refine agreements when predetermined conditions are met. This trustless automation reduces the need for intermediaries and increases operational efficiency.

#### 2.4 Distributed Storage Systems

Web3 also leverages distributed storage solutions such as the InterPlanetary File System (IPFS) to store data in a decentralized manner. This approach not only enhances data resilience and availability but also ensures that stored data remains tamper-proof.

### 3. Integration Mechanisms and Synergies

The synergy between large model agents and Web3 technologies creates powerful, next-generation applications:

#### 3.1 Decentralized Identity and Trust

Integrating blockchain-based identity verification with large model agents ensures that interactions are secure and verifiable. This decentralized authentication process ties digital identities to secure wallet addresses, enhancing trust in automated systems.

#### 3.2 Automated Smart Contract Execution

Large model agents can analyze data and trigger smart contract functions automatically. For example, an agent detecting market opportunities in decentralized finance (DeFi) might invoke a payment contract:

```
function executePayment(address recipient, uint amount) public {
    require(balance[msg.sender] >= amount, "Insufficient balance");
    balance[msg.sender] -= amount;
    balance[recipient] += amount;
    emit PaymentExecuted(msg.sender, recipient, amount);
}
```

Such automation reduces intermediaries and allows for real-time, trustless transactions.

#### 3.3 Transparent and Auditable Decision-Making

By recording every interaction on a blockchain, integrated systems allow for transparent audit trails. Each decision made by a large model agent can be logged immutably, ensuring accountability and traceability for all actions.

#### 3.4 Enhanced Scalability and Security

Combining the adaptive processing power of large models with blockchain's distributed architecture enhances both performance and security. Systems can scale horizontally, ensuring high concurrency while maintaining robust encryption and data integrity.

### 4. Detailed Application Scenarios

#### 4.1 Decentralized Finance (DeFi)

Large model agents can offer real-time analytics and trading strategies by processing vast amounts of financial data, while smart contracts execute transactions instantly and securely.

#### 4.2 Supply Chain Transparency

By merging large-scale data analysis with blockchain's immutable records, organizations can achieve complete traceability in supply chains, ensuring product authenticity and ethical sourcing.

#### 4.3 Content Creation and Rights Management

Large model agents generate high-quality content, and blockchain technology secures digital rights and ensures proper royalty distribution through automatic smart contract-based payments.

#### 4.4 Automated Contract Management

Agents can monitor contractual terms and automatically trigger actions in smart contracts, streamlining operations in various industries such as legal, real estate, and logistics.

### 5. Conclusion

The integration of large model agents, with their advanced neural architectures and emergent reasoning capabilities, and the decentralized, secure nature of Web3 creates a synergistic platform. This fusion not only enhances system security and transparency but also opens up innovative business models and scalable global solutions. The result is a revolutionary approach to intelligent systems that harnesses the best of both cutting-edge AI and blockchain technology.


# Architecture

## DeepCore Agent Architecture

### Overview

DeepCore's Agent Architecture is specifically designed for rapid, one-click creation of intelligent agents within the Web3 ecosystem. By leveraging a modular design that seamlessly integrates blockchain functionalities, DeepCore enables developers to instantiate, manage, and scale agents that can securely interact with decentralized networks and smart contracts.

### Agent Lifecycle

1. **Initialization:** Agents are dynamically created using a one-click interface. The system automatically loads pre-configured modules, relevant AI models, and blockchain integration components.
2. **Configuration:** Developers can customize agents with plug-and-play modules that include wallet authentication, smart contract interactions, and on-chain data processing capabilities.
3. **Execution:** Agents operate in a distributed environment, executing tasks such as data analysis, automated decision-making, and transaction management in real-time.
4. **Termination and Scaling:** Agents can be terminated, upgraded, or scaled horizontally based on workload demands, ensuring high availability and efficient resource management.

### Core Components

#### 1. Initialization Engine

* **Agent Generator:** Facilitates one-click creation by instantiating pre-built agent templates tailored for various Web3 use cases.
* **Module Loader:** Dynamically loads and integrates functional modules such as AI processing, decentralized identity verification, and blockchain connectivity.

#### 2. Execution Framework

* **Task Manager:** Orchestrates task scheduling and resource allocation across multiple agents to handle peak loads.
* **Communication Bus:** Ensures secure and reliable messaging between agents and external decentralized systems, leveraging encrypted channels and blockchain event logs.

#### 3. Customization and Extensibility

* **Plug-in System:** Supports third-party tool integrations and custom module development. Developers can extend functionality by adding modules that comply with DeepCore's API standards.
* **Configuration Service:** Provides an intuitive interface for updating agent parameters, security policies, and performance settings without downtime.

### Communication and Collaboration

DeepCore agents are designed to work collaboratively in multi-agent environments. Key features include:

* **Inter-Agent Communication:** Agents communicate using a standardized protocol to share information and coordinate tasks in a decentralized fashion.
* **Collaboration Framework:** Enables a group of agents to tackle complex workflows such as financial analysis, risk assessment, and decentralized governance by pooling their capabilities.

### Security and Blockchain Integration

Security is integral to the agent architecture, especially in the Web3 context:

* **Wallet-Based Authentication:** Agents authenticate through blockchain wallets, ensuring that only authorized users and systems interact with sensitive operations.
* **Smart Contract Integration:** Agents can execute, monitor, and verify smart contracts, thus automating processes like transactions, approvals, and audits in a trustless environment.
* **Data Integrity:** Employ cryptographic techniques to ensure that data processed and transmitted by agents maintains integrity and confidentiality.

### Sample Code Example

Below is an example demonstrating how to create and configure a Web3-enabled agent using DeepCore:

```
from deepcore import Agent, Team
from deepcore.tools import BlockchainConnector, SmartContractExecutor, AIAgentCore
​
# Create a team with a Web3-enabled agent
web3_agent_team = Team(
    name='web3_agents',
    agents=[
        Agent(
            name='agent_alpha',
            tools=[
                AIAgentCore(),
                BlockchainConnector(),
                SmartContractExecutor()
            ]
        )
    ]
)
​
# Initialize and execute an agent task
result = web3_agent_team.handle_request('Execute smart contract for token transfer')
print(result)
```

### Conclusion

DeepCore's Agent Architecture delivers a robust, scalable, and secure framework for intelligent agent deployment in the Web3 domain. With its one-click creation capability, modular design, and seamless blockchain integration, DeepCore empowers developers to build next-generation decentralized applications with minimal effort and maximum efficiency.


# Performance

## DeepCore Performance Optimization

### Introduction

DeepCore is designed to deliver high performance in the demanding environment of Web3 applications. The following guidelines outline best practices for optimizing system performance, including load balancing, caching, database tuning, scalable system architectures, and continuous performance monitoring.

### Load Balancing

* **Horizontal Scaling:** Distribute workload across multiple instances of agents to handle increased traffic.
* **Application Load Balancers:** Use load balancers (e.g., NGINX, HAProxy, Kubernetes Ingress) to distribute requests evenly across all instances.
* **Global Traffic Management:** Implement global load balancing solutions to direct traffic based on geographic regions, improving latency and user experience.

### Caching Strategies

* **In-Memory Caching:** Use Redis or Memcached to cache frequent queries and reduce database load.
* **Content Delivery Networks (CDNs):** Cache static assets at edge locations to decrease latency and bandwidth usage.
* **API Response Caching:** Implement HTTP caching headers for API responses to speed up client-side performance.

### Database Optimization

* **Indexing:** Ensure proper indexing on frequently queried fields to reduce query execution time.
* **Query Optimization:** Analyze and optimize slow queries using database profiling tools.
* **Read Replicas:** Utilize database read replicas to distribute read-heavy workloads and improve query performance.

### Scalable Architectures

* **Microservices:** Break down the application into microservices to isolate performance bottlenecks and scale them independently.
* **Serverless Functions:** Leverage serverless computing for asynchronous processing and to handle variable loads efficiently.
* **Container Orchestration:** Use Kubernetes to manage containerized deployments, enabling automated scaling and resource management.

### Performance Monitoring

* **Metrics Collection:** Use tools like Prometheus to collect system metrics (CPU, memory, network I/O).
* **Visualization:** Implement Grafana dashboards to visualize performance metrics and pinpoint bottlenecks.
* **Alerting:** Set up alerts for key performance indicators (latency, error rates, throughput) to detect and mitigate issues promptly.

### Conclusion

By implementing these performance optimization techniques, DeepCore can maintain high efficiency and reliability even under heavy load. Continuous improvement and monitoring will ensure that your Web3 applications run smoothly and deliver a superior user experience.


# Use-Cases

## DeepCore Use Cases and Best Practices

DeepCore is designed to simplify the creation and deployment of intelligent agents with a single click, specifically tailored for the Web3 ecosystem. This document outlines a range of practical applications, innovative scenarios, and industry solutions that leverage DeepCore's seamless integration of AI and decentralized technologies.

<figure><img src="https://1759951032-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvilI5gkHSwBtnpgNfbRd%2Fuploads%2FBxqfI3HAEtcPATHI0Tr5%2Fimage.png?alt=media&amp;token=2f558b50-07b0-4a26-9177-283b11336af8" alt=""><figcaption></figcaption></figure>

### 1. Core Application Scenarios

#### Decentralized Customer Service

Leverage DeepCore's one-click agent creation to deploy customer service assistants that can interact not only with users but also verify blockchain identities and manage smart contracts for transactions. This decentralized approach ensures transparency and enhanced security.

**Technical Implementation Example:**

```
from deepcore import Agent, Team
from deepcore.tools import CustomerService, WalletValidator, SmartContractHandler
​
# Create a decentralized customer service team
support_team = Team(
    name='decentralized_support',
    agents=[
        Agent(name='frontline', tools=[CustomerService(), WalletValidator()]),
        Agent(name='backend', tools=[SmartContractHandler()])
    ]
)
​
# Process a customer request with blockchain verification
response = support_team.handle_request('Request refund with wallet authentication')
print(response)
```

#### Web3 Data Analytics

Deploy agents to analyze on-chain data and decentralized transaction logs. These agents can perform trend analyses, anomaly detection, and real-time reporting of blockchain activities, enabling enterprises to make data-driven decisions in the Web3 space.

**Technical Implementation Example:**

```
from deepcore import Agent
from deepcore.tools import DataAnalyzer, BlockchainVisualizer
​
# Initialize an analytics agent with Web3 tools
analytics_agent = Agent(
    name='web3_analyst',
    tools=[DataAnalyzer(), BlockchainVisualizer()]
)
​
# Analyze on-chain sales data
analysis_report = analytics_agent.analyze('blockchain_sales_data.csv')
print(analysis_report)
```

#### Content Creation and Distribution

Utilize DeepCore agents to generate, edit, and optimize content for decentralized platforms. These agents can create articles, manage digital assets such as NFTs, and distribute content across various blockchain-powered networks.

**Technical Implementation Example:**

```
from deepcore import Team
from deepcore.tools import ContentCreator, SEOTool
​
# Set up a content team for creating engaging articles for Web3 platforms
content_team = Team(
    name='content_creators',
    agents=[
        Agent(name='writer', tools=[ContentCreator()]),
        Agent(name='optimizer', tools=[SEOTool()])
    ]
)
​
# Generate and optimize content
article = content_team.create_content('The Future of Web3 and AI Integration')
print(article)
```

### 2. Innovative Application Scenarios

#### Decentralized R\&D Assistant

Combine AI-driven code analysis with blockchain-based version control and smart contract audits. This assistant can perform code reviews, conduct security audits on decentralized applications, and suggest improvements in real time.

**Technical Implementation Example:**

```
from deepcore import Agent
from deepcore.tools import CodeReviewer, SmartAuditTool, TestCaseGenerator
​
r_and_d_assistant = Agent(
    name='r_and_d_assistant',
    tools=[CodeReviewer(), SmartAuditTool(), TestCaseGenerator()]
)
​
# Perform a secure code review integrated with blockchain audit
review = r_and_d_assistant.review_code('dapp_main.py')
print(review)
```

#### Web3 Education System

Develop an educational platform that uses intelligent agents to provide personalized learning experiences for blockchain and decentralized technology topics. The agents can assess user progress, deliver targeted tutoring, and issue blockchain-verified certificates.

**Technical Implementation Example:**

```
from deepcore import Team
from deepcore.tools import Tutor, ProgressTracker
​
education_team = Team(
    name='web3_education',
    agents=[
        Agent(name='tutor', tools=[Tutor()]),
        Agent(name='tracker', tools=[ProgressTracker()])
    ]
)
​
# Provide personalized learning guidance with certificate issuance
guidance = education_team.provide_guidance('student_42')
print(guidance)
```

#### Blockchain Financial Analysis Assistant

Deploy intelligent agents that can analyze crypto market trends, assess risks, and generate reports for investors. By integrating with decentralized finance (DeFi) protocols, these agents provide real-time insights for financial decision-making in the blockchain ecosystem.

**Technical Implementation Example:**

```
from deepcore import Agent, Team
from deepcore.tools import MarketAnalyzer, RiskAssessor, ReportGenerator
​
finance_team = Team(
    name='crypto_finance',
    agents=[
        Agent(name='analyst', tools=[MarketAnalyzer()]),
        Agent(name='risk_manager', tools=[RiskAssessor()]),
        Agent(name='reporter', tools=[ReportGenerator()])
    ]
)
​
# Analyze the crypto market and generate a financial report
financial_report = finance_team.analyze_market('Ethereum')
print(financial_report)
```

### 3. Industry Solutions

DeepCore's versatility allows it to be applied across a range of industries that are beginning to embrace decentralized technologies:

#### Healthcare

* **Decentralized Patient Data Management**: Secure patient data on the blockchain, ensuring privacy, and enabling real-time medical record access and verification.
* **Smart Clinical Trials**: Manage patient consent, trial data, and results using smart contracts for enhanced transparency and credibility.

#### Manufacturing

* **Supply Chain Transparency**: Utilize blockchain integration to track product provenance and optimize logistics in a decentralised manufacturing ecosystem.
* **Predictive Maintenance**: Deploy agents to analyze IoT data combined with blockchain records for more accurate and timely maintenance decisions.

#### Smart Cities

* **Decentralized Governance**: Implement intelligent agents for managing public services, energy grids, and municipal operations with blockchain-enabled trust and transparency.
* **Urban Analytics**: Harness on-chain data and AI to analyze city trends, leading to better resource management and urban planning.

### 4. Effectiveness Evaluation

The performance and impact of DeepCore agents can be evaluated based on several metrics:

#### Performance Metrics

* **Response Time**: Average response time should be under 100ms for interactive applications.
* **Accuracy**: AI-driven decisions should achieve accuracy levels above 95%.
* **Scalability**: System should support high concurrency, handling thousands of simultaneous requests.
* **Uptime**: Maintain 99.99% availability with robust failover mechanisms.

#### Business Impact

* **Cost Efficiency**: Significant reduction in operational costs through automation of tasks.
* **Process Optimization**: Improved process efficiency and reduced time-to-market for decentralized applications.
* **User Engagement**: Enhanced customer and user satisfaction through personalized, secure interactions.

#### Social Impact

* **Decentralization Benefits**: Empower users by redistributing control from centralized entities to community-governed platforms.
* **Innovation Ecosystem**: Foster collaboration and innovation across communities, startups, and enterprises in the Web3 space.
* **Sustainable Growth**: Support long-term economic and technological sustainability within decentralized economics.

DeepCore continually evolves to meet the diverse needs of Web3 applications, ensuring that our intelligent agents deliver both cutting-edge performance and tangible business value in a decentralized world.


# Web3 Integration Guide

## DeepCore Web3 Integration Guide

### Introduction

DeepCore is designed to bridge the gap between advanced artificial intelligence and decentralized technologies in the Web3 ecosystem. This guide provides a comprehensive overview of how to integrate DeepCore with blockchain networks, deploy smart contracts, and utilize wallet authentication to power AI-driven decentralized applications.

### Integration Architecture

DeepCore integrates with various blockchain networks using a modular and secure approach. Key components include:

* **Blockchain Connectors:** Modular components that connect to blockchain nodes (e.g., Ethereum, Binance Smart Chain).
* **Wallet Authentication:** Mechanisms to verify user identities via decentralized wallet signatures.
* **Smart Contract Interfaces:** APIs for deploying, interacting with, and monitoring smart contracts on the blockchain.
* **Data Synchronization:** Real-time tracking of on-chain events and transactions to update agent states.

### Connecting to Blockchain Networks

DeepCore provides pre-configured blockchain connectors that allow for seamless communication with decentralized networks. These connectors can be customized based on the target blockchain's parameters. For example, connecting to Ethereum can be achieved by configuring the provider URL and network ID.

#### Example: Ethereum Connection

Below is a sample code snippet demonstrating how to connect DeepCore to the Ethereum network using a connector module:

```
from deepcore.tools import BlockchainConnector
​
# Initialize a blockchain connector for Ethereum
eth_connector = BlockchainConnector(
    provider_url='https://mainnet.infura.io/v3/YOUR_INFURA_PROJECT_ID',
    network_id=1
)
​
# Test connection by fetching the latest block number
latest_block = eth_connector.get_latest_block()
print(f'Latest Ethereum Block: {latest_block}')
```

### Smart Contract Integration

DeepCore agents can interact with smart contracts to execute transactions, trigger events, and automate decentralized workflows. The platform provides a Smart Contract Executor tool that abstracts the complexities of contract interactions.

#### Deploying and Interacting with a Smart Contract

Below is an example of deploying a simple smart contract and invoking its functions:

```
from deepcore.tools import SmartContractExecutor
​
# Define the smart contract's ABI and bytecode
contract_abi = [
    {
        "constant": False,
        "inputs": [{"name": "_value", "type": "uint256"}],
        "name": "setValue",
        "outputs": [],
        "type": "function"
    },
    {
        "constant": True,
        "inputs": [],
        "name": "getValue",
        "outputs": [{"name": "", "type": "uint256"}],
        "type": "function"
    }
]
contract_bytecode = "0x608060405234801561001057600080fd5b50610107806100206000396000f3fe6080604052600436106100295760003560e01c8063"  
​
# Initialize a smart contract executor
contract_executor = SmartContractExecutor(
    connector=eth_connector,
    abi=contract_abi
)
​
# Deploy the smart contract
contract_address = contract_executor.deploy(bytecode=contract_bytecode, deploy_args=[123])
print(f'Deployed Contract Address: {contract_address}')
​
# Call a contract function
tx_hash = contract_executor.call_function(
    contract_address,
    function_name='setValue',
    args=[456]
)
print(f'Transaction Hash: {tx_hash}')
```

### Wallet Authentication in Web3

DeepCore leverages wallet-based authentication to ensure secure and decentralized access. Users sign a nonce sent by the platform, and the signature is verified to authenticate access without compromising private keys.

#### Wallet Authentication Workflow

1. **Request a Nonce:** The client requests a unique nonce from DeepCore.
2. **Sign the Nonce:** The user signs the nonce using their blockchain wallet.
3. **Verify Signature:** The signature is sent back to DeepCore for verification, granting access upon success.

This mechanism ensures that only the legitimate owner of a wallet can perform sensitive operations on the platform.

### Best Practices for Web3 Integration

* **Secure Provider URLs:** Always use secure endpoints (HTTPS) and protect API keys for blockchain node providers.
* **Robust Error Handling:** Implement retries and fallback mechanisms for handling network interruptions.
* **Smart Contract Audits:** Regularly audit smart contracts for vulnerabilities and update them as needed.
* **Wallet Security:** Educate users about safeguarding their private keys and using hardware wallets where possible.
* **Scalability:** Use load balancing and caching strategies to handle high transaction volumes and real-time data synchronization.

### Historical Perspective (2015 Edition)

In 2015, blockchain technology was still emerging and the concept of Web3 was in its infancy. During this period, early experiments focused on straightforward blockchain connectivity using basic HTTP APIs, rudimentary smart contract deployments, and experimental wallet authentication methods. These initial implementations were often manual and lacked the automation and sophistication of today's systems. However, they laid the essential groundwork by highlighting the potential of decentralized networks and demonstrating that even simple integrations could unlock new possibilities. The foundational lessons learned during this time continue to influence the modern, robust Web3 integration strategies employed by DeepCore.

### Conclusion

DeepCore's Web3 Integration Guide illustrates the platform's ability to seamlessly integrate with blockchain networks, enabling secure and efficient interactions with smart contracts and decentralized applications. By following these guidelines and best practices, developers can build robust AI-powered solutions that fully leverage the potential of the Web3 ecosystem.


# Ecosystem

## DeepCore Community and Ecosystem

### Community Overview

#### Developer Community

* **Global Developer Networks:** Engage a worldwide network of developers dedicated to the advancement of AI and decentralized technologies.
* **Expert Committees:** Composed of industry pioneers and academic experts who review and support community projects and contributions.
* **Community Operations Team:** Manages forums, support channels, and live events to keep the community active and informed.
* **Knowledge Sharing Initiatives:** Regular webinars, hackathons, and discussion groups that foster collaboration and innovation in the Web3 space.

#### Community Activities

* **Global Developer Conferences:** Annual events to showcase innovation, share technical breakthroughs, and foster collaboration.
* **Online Workshops and Webinars:** Deep-dive sessions on using DeepCore for AI and decentralized application development.
* **Hackathons and Competitions:** Events designed to challenge developers and encourage creative solutions using one-click agent technology.
* **Technical Meetups:** Regular meetings to discuss trends, share knowledge, and refine best practices in AI and blockchain integration.
* **Training Sessions:** Workshops and certification programs that provide hands-on expertise and validate technical skills.

### Partner Ecosystem

#### Strategic Collaborations

* **Blockchain Service Providers:** Partnerships with leading blockchain networks to ensure seamless, secure integration.
* **Open Source Communities:** Collaborative projects and initiatives that promote innovation and transparency in the decentralized ecosystem.
* **Fintech and DeFi Innovators:** Joint development of solutions tailored to decentralized finance, NFTs, and digital asset management.
* **Technology Consortia:** Alliances with industry leaders to set new standards in AI, blockchain interoperability, and decentralized technologies.
* **Academic and Research Institutions:** Collaborations to advance the study of AI, blockchain technology, and their convergence in the Web3 domain.

### Ecosystem Building

#### Developer Support

* **Comprehensive Documentation:** Detailed guides, API references, tutorials, and sample code to accelerate one-click intelligent agent creation.
* **Pre-built Templates and Modules:** A rich library of reusable components for rapid prototyping of Web3 applications.
* **Online Knowledge Hub:** A central repository for blogs, video tutorials, and community-driven content to support continuous learning.
* **Open Source Programs:** Incentivized initiatives for community members to contribute, review, and improve DeepCore's platform.

#### Training and Certification

* **Structured Learning Programs:** Courses ranging from introductory to advanced levels covering AI, blockchain integration, and secure decentralized application development.
* **Certification Tracks:** Formal certification paths that validate skills in AI agent deployment, Web3 integration, and blockchain security.
* **Workshops and Bootcamps:** Intensive, hands-on training sessions aimed at real-world project development and industry readiness.
* **Developer Incentives:** Recognition programs and rewards to motivate and sustain active community contributions.

### Ecosystem Value Proposition

#### Commercial Value

* **Economic Growth:** Unlock new revenue streams for businesses by enabling innovative Web3 applications powered by AI automation.
* **Market Expansion:** Leverage strategic partnerships and global networks to penetrate diverse markets and accelerate adoption.
* **Revenue Opportunities:** Monetize through premium enterprise features, consulting, and bespoke integrations tailored for the decentralized ecosystem.
* **Innovation Catalyst:** Drive continuous innovation by combining cutting-edge AI with decentralized technologies to redefine industry standards.

#### Social Value

* **Decentralized Empowerment:** Empower users by shifting control from centralized authorities to community-governed platforms, fostering transparency and trust.
* **Talent Development:** Cultivate a new generation of developers skilled in both AI and blockchain, contributing to a robust innovation pipeline.
* **Community Collaboration:** Strengthen the open-source culture through shared knowledge and collaborative problem-solving.
* **Global Impact:** Contribute to sustainable economic growth and digital inclusion on a global scale.

### Ecosystem Operations

#### Community Management

* **Content Strategy:** Regular publication of high-quality tutorials, case studies, and success stories that highlight the capabilities of DeepCore.
* **Engagement Metrics:** Monitor community activity and feedback to continuously improve engagement strategies and support resources.
* **Event Coordination:** Organize both virtual and in-person events that promote networking, learning, and collaboration.

#### Partner Initiatives

* **Joint Ventures:** Collaborate on pilot projects to explore new applications of decentralized AI technology.
* **Technical Co-development:** Work closely with partners to refine and extend DeepCore's capabilities, ensuring alignment with market needs.
* **Strategic Alliances:** Build long-term relationships with key players in blockchain and AI to drive platform adoption and innovation.

### Internationalization and Future Outlook

#### Global Expansion

* **Localization:** Offer multi-language support and region-specific content to cater to a diverse global audience.
* **International Partnerships:** Establish alliances with regional blockchain hubs and technology clusters worldwide.
* **Global Conferences:** Participate in and host international events to showcase innovative use cases and share best practices.
* **Future Ecosystem Development:** Continuously evolve the platform to meet emerging trends and technological advancements in the Web3 space.


# Security

## DeepCore Security Best Practices

### Introduction

DeepCore is built to operate in the dynamic and decentralized landscape of Web3. To ensure the integrity, confidentiality, and availability of your applications, it is essential to adhere to high security standards. This document outlines the security best practices that should be implemented when deploying and managing DeepCore.

### Authentication and Authorization

* **JWT and Wallet-Based Authentication:** Use secure JSON Web Token (JWT) mechanisms and decentralized wallet signatures to verify the identity of users and agents.
* **Multi-Factor Authentication (MFA):** Where applicable, enforce MFA to add an extra layer of security.
* **Role-Based Access Control (RBAC):** Adopt the principle of least privilege by assigning the minimum permissions necessary for each role.

### Data Encryption and Storage Security

* **Encryption in Transit:** All data exchanged between clients, agents, and the backend must be encrypted using TLS/SSL protocols.
* **Encryption at Rest:** Implement encryption for all stored data, including databases and file systems.
* **Key Management:** Use hardware security modules (HSM) or secure vaults to manage and store cryptographic keys.

### Blockchain and Smart Contract Security

* **Smart Contract Audits:** Regularly perform comprehensive audits of smart contracts to ensure they are free from vulnerabilities.
* **Wallet Security:** Enforce wallet-based authentication to verify identities and safeguard access to sensitive operations on the blockchain.
* **Secure Key Handling:** Ensure that private keys used in blockchain operations are stored securely and are never exposed in plaintext.

### Agent Security

* **Regular Updates:** Keep all agent components updated to mitigate security vulnerabilities.
* **Secure Communication:** Ensure that communication between agents and the control plane is encrypted and authenticated.
* **Anomaly Detection:** Monitor agent activities continuously and implement anomaly detection to identify any suspicious behavior.

### Network and Infrastructure Security

* **Network Segmentation:** Utilize firewalls and virtual private networks (VPNs) to segment and isolate critical services within your network.
* **Kubernetes Security:** Apply Kubernetes Network Policies and utilize container security contexts to restrict inter-pod communication.
* **Regular Patching:** Keep all operating systems, containers, and software dependencies up-to-date with the latest security patches.

### Logging, Monitoring, and Incident Response

* **Centralized Logging:** Implement centralized logging solutions (e.g., ELK stack, Fluentd) to aggregate logs from all components for real-time analysis.
* **Continuous Monitoring:** Use monitoring tools like Prometheus and Grafana to track system performance and detect anomalies.
* **Audit Trails:** Maintain detailed logs of all security-related events and changes to aid in forensic analysis during incident investigations.
* **Incident Response Plan:** Develop and regularly update an incident response plan that includes procedures for detecting, responding to, and recovering from security incidents.


# RoadMap

**2025-2026: Technology Development & Protocol Maturity**\
**2027+: Ecosystem Expansion & Industry Benchmark Building**

***

#### **I. 2025-2026: Core Protocol Development & Ecosystem Foundation**

**2025**

* **Q1**
  * **Team Formation & Product Conceptualization Completed**: Core team assembled and product vision finalized.
  * **Agent-Core Protocol Layer 1.0 Development Completed**: Initial version of the Agent-Core protocol layer ready for deployment.
  * **DeepCore AI Agent Deployment Platform Completed**: Platform for deploying AI Agents fully developed.
  * **Solana Native Integration**: Deep integration of Agent-Core with Solana oracle network (latency <0.3 seconds).
  * **Developer Toolkit Beta Launch**: Release of visual orchestrator and debugging simulator to 1,000 early developers.
* **Q2**
  * **DeepMatrix Appstore Launch**: Basic AI Agent store functionality with support for 10 modular templates.
  * **HIVE 1.0 Deployment**: Real-time collaboration network supporting 100+ AI Agents; release of HIVE protocol whitepaper.
  * **Cross-Chain Interoperability Testing**: Implementation of Solana Fusion protocol for bidirectional asset transfers with Ethereum, Base and BNB Chain.
  * **First Developer Incentive Program**: Establishment of DeepCore Ecosystem Fund to support 50 AI Agent innovation projects.
* **Q3**
  * **TokenForge Launchpad Launch**.
  * **HIVE 2.0 Release**: Support for 10,000+ Agent dynamic collaboration with latency reduced to 0.1 seconds.
  * **Enterprise Partnership Program**: Collaboration with 20 Solana ecosystem leaders to build AI Agent solutions.

***

**2026**

* **Q1**
  * **AI Protocol Standardization**: Leading the development of Web3 Agent Interaction Protocol Standard (W3A-Protocol).
  * **Federated Learning Framework Open-Sourced**: Developers can train compliant AI models using private data.
  * **On-Chain Governance Module Launch**: $DCORE holders can vote on protocol upgrades.
* **Q2**
  * **Multi-Chain AI Execution Environment**: covering 80% of mainstream blockchains.
  * **Protocol Autonomy**: 90% of protocol upgrade proposals generated by AI analysis systems.
  * **Dynamic Liquidity Engine**: Integration with Solana DEX aggregator, reducing AI strategy trading slippage by 40%.
* **Q3**
  * **AI Self-Evolving Protocol**: Introduction of reinforcement learning-driven architecture optimization, enabling daily parameter updates.
  * **Enterprise SaaS Platform Launch**: Release of a compliant DeepCore Cloud for financial institutions and government projects.
  * **Completion of Full Platform Development**: Finalization of platform development with cutting-edge technology research and integration.
* **Q4**
  * **Developer Ecosystem Expansion**: Registered developers exceed 100,000, with over 5,000 Agents listed in the store.
  * **Hybrid Oracle Network**: Expansion of off-chain data sources to IoT devices and satellite data, supporting real-world asset (RWA) scenarios.
  * **AI Economy Formation**: Platform AI service transaction volume targets $1 billion, accounting for 12% of Solana ecosystem transactions.

***

#### **II. 2027+: Ecosystem Expansion & Industry Benchmark Building**

**1. Becoming the Web3 AI Infrastructure Standard**

* **Market Share**: Covering 80% of Web3 AI application development needs.
* **Technology Export**: Providing standardized Agent-Core protocol licensing to other blockchains.

**2. Global Partner Network**

* **Enterprise Alliance**: Formation of the #RWA Alliance to expand industry solutions to real-world enterprises (finance, healthcare, manufacturing).
* **Developer Ecosystem**: Establishment of 10 regional developer hubs (Silicon Valley, Singapore, Berlin, etc.).

**3. Platform AI Agent Competition System**

* **Annual Global Challenge**:
  * $10 million prize pool for the best DeFi strategies, social governance, and other track Agents.
  * Winning Agents integrated into Solana core ecosystem projects (e.g., Greenfield storage network).

**4. User & Data Scale**

* **C-End User Growth**:
  * 50% of users building personalized applications through natural language interaction.
* **Data Assetization Platform**:
  * Hosting PB-level on-chain/off-chain data assets.
  * Strengthening the AI training data trading market.

***

#### **DeepCore’s Ultimate Goal**

DeepCore aims to make every individual an equal participant in the AI economy—where creativity is capital, collaboration is value, and the future is written by code and consensus.


# Token Economics

($DPCORE rules and thinking in...)


# Vision & Path

### **I. Vision & Path: The Intelligent Foundation of Web3 Civilization**

**1. Protocol Layer Revolution**

* **DCP-Core Protocol**:
  * Standardizes AI Agent interaction, collaboration, and value exchange as "TCP/IP for AI."
  * Through our independently developed DCP Agent Interaction Protocol, you can build Agents and complex workflows on top of LLMs (Large Language Models).
* **Developer Toolkit Suite**:
  * DeepCore is building a GitHub-style collaborative ecosystem for AI development, offering privacy-preserving and compliant AI development tools.

**2. AI-App Store**

* **DeepMatrix Store**:
  * We named DeepCore's AI App Store "DeepMatrix Store": the world's first AI-App Store that grows with the ecosystem, allowing users to modularly compose and purchase AI applications.
* **TokenForge Engine**:
  * Transforms AI capabilities into tradable on-chain assets (tokenization), unlocking trillion-dollar long-tail value.

**3. Self-Evolving Ecosystem**

* **HIVE Collaboration Network**: Millions of AI Agents autonomously collaborate via game theory models, fostering on-chain swarm intelligence
* **Developer Flywheel**: Royalty distribution, liquidity incentives, and tokenized governance form a growth loop.

<figure><img src="https://1759951032-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvilI5gkHSwBtnpgNfbRd%2Fuploads%2FuJpTGw0FLbXsol82o6SO%2Fimage.png?alt=media&amp;token=645ee24f-8cb3-4f5e-bafd-043ce7d16953" alt=""><figcaption></figcaption></figure>

***

## **II. 2025 Milestones: Setting Industry Standards**

#### **Goals: By 2025, DeepCore Will Achieve**

* **10,000+ composable AI Agent modules**, covering DeFi, social, trading, gaming, cultural applications, and more.
* **500,000+ users** building personalized Web3 applications through DeepCore Workshop.
* **$5 billion+ on-chain AI economy**, accounting for 10% of BNB Chain's total ecosystem value.

<table data-header-hidden><thead><tr><th width="195"></th><th width="256"></th><th></th></tr></thead><tbody><tr><td><strong>Metric</strong></td><td><strong>Target</strong></td><td><strong>Industry Impact</strong></td></tr><tr><td><strong>Composable AI Modules</strong></td><td>10,000+ (covering DeFi, gaming, social)</td><td>Become the largest AI development ecosystem in Web3</td></tr><tr><td><strong>User Base</strong></td><td>500,000+ (70% via natural language interaction)</td><td>Drive a 300% increase in no-code development adoption</td></tr><tr><td><strong>On-Chain AI Economy</strong></td><td>$5 billion+ (10% of BNB Chain ecosystem value)</td><td>Establish as the benchmark protocol for AI and Web3 integration</td></tr></tbody></table>


# Market Positioning

Multi-Agent LLM Framework, Revolutionizing AI Agent with BNB CHAIN.

### **“Building Web3's AI Agent Cornerstone to make the AI Agent the basic unit of Crypto's new civilization.”**

DeepCore is not just an AI platform, but a revolutionary ecosystem dedicated to reinventing the way AI is developed and interacted with. We provide an innovative decentralized AI ecosystem for developers and end users based on the BNB Chain.

**For developers**

> DeepCore provides a revolutionary platform that makes it easy to create, deploy and manage complex AI agents.

**For end-users**

> DeepCore has launched the DeepMatrix AI Agent Store, which allows users to freely combine the required Web3-enabled AI Agents to meet their individual needs, just like building Legos.

Our goal is to popularize AI Agent like mobile apps, helping developers and enterprises to easily create, deploy and manage complex AI solutions, while revolutionizing the operational model and user experience in the Web3 space. Through the power of Intelligent Agents, DeepCore will be the cornerstone of a decentralized future, driving more efficient and smarter Web3 innovation.

## DeepCore Market Positioning and Competitive Advantage Analysis

### Market Positioning

#### Product Positioning

DeepCore is positioned as an enterprise-grade intelligent agent platform designed specifically for the Web3 ecosystem. Our platform simplifies the creation, deployment, and management of AI assistants by combining advanced artificial intelligence with decentralized technologies. DeepCore enables organizations, developers, and enterprises to build agents that interact with blockchain networks, manage smart contracts, and drive automation in decentralized environments.

#### Target Market

* **Web3 Developers**: Independent developers and small teams creating decentralized applications.
* **Blockchain Startups**: Companies innovating in decentralized finance, NFTs, and digital assets.
* **Enterprises**: Organizations seeking secure, scalable solutions for AI-powered Web3 applications.
* **Decentralized Communities**: DAOs and open-source communities focused on building trustless systems.

#### Market Size

* The global Web3 market is rapidly expanding, with projections reaching multi-billion-dollar valuations in the coming years.
* DeepCore targets a diverse audience spanning startups, mid-market businesses, and large enterprises embracing blockchain technologies.
* With the anticipated surge in decentralized applications, DeepCore aims to capture a significant share of this burgeoning market.

### Competitive Advantages

#### Technical Advantages

* **Seamless Web3 Integration**: Built-in support for blockchain identity verification, decentralized data storage, and smart contract interactions.
* **State-of-the-Art Architecture**: Advanced multi-agent frameworks and reasoning engines delivering efficient performance and scalability.
* **Robust Security**: Enterprise-grade security measures including wallet-based authentication and cryptographic validations to protect sensitive operations.

#### Product Advantages

* **One-Click Agent Creation**: Rapid deployment of fully functional AI agents with minimal setup, streamlining innovation.
* **Highly Customizable Modules**: A rich library of modular tools and plug-ins that can be tailored for various Web3 use cases.
* **Rapid Prototyping**: Accelerated development cycles that allow for quick iterations and real-time testing of new ideas.

#### Market Advantages

* **First-Mover Benefit**: Leveraging early adoption within the niche of AI-powered Web3 solutions to establish market leadership.
* **Vibrant Ecosystem**: Strong community engagement and strategic partnerships with key players in the blockchain space amplify our market presence.
* **User-Centric Design**: Intuitive interfaces and low-code development tools enhance user engagement and reduce onboarding time.


# Contact Us

## **Join DeepCore, Join the Future of AI** <a href="#ii.-join-deepcore-join-the-future-of-ai" id="ii.-join-deepcore-join-the-future-of-ai"></a>

*/ Real change is only possible when transformative technology meets exceptional talent.*\
*/ And that's just the beginning.*\
*/ Will you be a catalyst or a bystander in this revolution?*

### Ready to revolutionize your AI development?

* X: [@deepcore\_io](https://x.com/deepcore_io)
* Website: [www.deepcore.top](http://www.deepcore.top)
* GitHub: github.com/deepcore

### Support

Need help? Here are your options:

1. Check our [documentation](https://github.com/0xdevpro/deepcore)
2. Open an issue on [GitHub](https://github.com/0xdevpro/deepcore)

###


